using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web.Configuration;

public partial class OpenAuthorMode : System.Web.UI.Page
{
    String interactiveUpdateTemporaryComment = ";;";
    string SaveNotificationComment = ";--------------" + System.Environment.NewLine;

    public Data.VarParams varParam = null;
    public Data.DataConsolidation dc = null;
    public Data.Data currentData = null;
    LoginHelper lh = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        lh = new LoginHelper(this);

        String myDataDir = (String)Session["MyApplicationDirectory"];
        if (myDataDir == null)
        {
            myDataDir = Request.Params["a"];
            if (myDataDir == null)
                Response.Write(" Your session is expired or this page wasn't started correctly. Try starting it with ?a=windmill for our demo data.");
        }

        String myApplicationDir = Request.PhysicalApplicationPath + myDataDir;
        varParam = new Data.VarParams();
        String errMsg = varParam.ReadFile(myApplicationDir, this.Session.SessionID);
        if (errMsg != null)
        {
            ViewProjectForm.Visible = false;
            Response.Write(errMsg);
            return;
        }

        if( IsPostBack == false )
            FilenameToSaveTo.Text = lh.GetProjectCaption();

        if (DoProcessProject(true, ViewState))
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            if (currentPage != null)
            {
                if (IsPostBack == false)
                {
                    LoadControlsThatNeedFreshData(currentPage);
                    populateProjectScriptBox();
                }
                makeChart(false);
            }
            else
            {
                DoShowEventLogDlg();
            }
        }
        else
        {
            if (ErrorMessage.Visible == false)
            {
                ErrorMessage.Visible = true;
                populateProjectScriptBox();
                ErrorMessage.Text = "Encountered a problem in this project. See the Event Log for Details or press the back button to return to where you were before the error.<br />";
                // btnShowEventDialog.Visible = true;
                MyControls.Visible = false;
                DoShowEventLogDlg();
            }
        }
    }

    bool DoProcessProject(bool siteLicense, StateBag ViewState)
    {
        dc = new Data.DataConsolidation(varParam);

        currentData = new Data.Data();
        if (currentData == null)
            return false;

        bool result = DoProject.ExecuteProjectFile( FilenameToSaveTo.Text, varParam, dc, currentData, IsPostBack);
        if (result == false)
            return false;

        // next we read the ViewState to see if there are any transactions there
        if (currentData.GetPageCount() > 0)
        {
            List<String> updates = (List<String>)ViewState["InteractiveUpdates"];
            if ( updates != null)
            {
                int count = updates.Count;
                for ( int i = 0; i < count; i++)
                {
                    string thisScriptItem = updates[ i ];
                    runScript(thisScriptItem, currentData, IsPostBack == false);
                }
            }
        }


        string desiredPageCaption = lh.GetPageCaption();
        if (desiredPageCaption != null)
        {
            /* if given a page caption, attempt to use it. Since this is the last instruction given, then 
             * it overrides whatever the selectedpage was in the command script */
            currentData.SetSelectedPage(desiredPageCaption);
        }

        Data.MyListString results = new Data.MyListString();
        OutputDbTable.RunExecutedProjectToSql(results, currentData);
        String fileNameToSaveTo = varParam.GetMyDataDir() + lh.GetProjectCaption() + ".sql";
        Data.MyFile.WriteAllLines(varParam, fileNameToSaveTo, results);
        return true;
    }

    private bool runScript(string thisScriptItem, Data.Data currentData, bool initialLoad)
    {
        bool success = dc.RunScript(thisScriptItem, currentData, initialLoad);
        if (success)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
        }
        return success;
    }

    private void findFocus(Panel visiblePanel)
    {
        // MyControls.Visible = false;
        visiblePanel.Visible = true;
        //
        // look at the controls in Visible Panel. If one them is a button that has Text='OK' then make it the page default button
        foreach (Control control in visiblePanel.Controls)
        {
            string type = control.GetType().ToString();
            if (type.IndexOf(".button", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                Button btn = (Button)control;
                string text = btn.Text;
                if (text.Equals("OK", StringComparison.CurrentCultureIgnoreCase))
                {
                    control.Focus();
                    // this.SetFocus(control);
                    return;
                }
            }
        }

        //
    }

    protected void HandleMenuItemClick(object sender, MenuEventArgs e)
    {
        this.closeAllDlgs();
        string id = e.Item.Value;

        string cmd = "script" + MyVariables.DelimForTokens;

        if (id.IndexOf(".aspx", StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            Response.Redirect(id);
            return;
        }
        else if (id.IndexOf(cmd, StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            string serverCommand = id.Remove(0, cmd.Length);
            doCommonPostback(serverCommand, sender);
            return;
        }
        else if (id.IndexOf("doShowRenamePageCaption", StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            doShowRenamePageCaption(sender, null);
            return;
        }
        else if (id.Equals("SAB1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowAsPanel1); }
        else if (id.Equals("SAB2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowAsPanel2); }
        else if (id.Equals("SAB3", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowAsPanel3); }
        else if (id.Equals("SAB4", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowAsPanel4); }
        else if (id.Equals("SAB5", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowAsPanel5); }
        else if (id.Equals("CompareSimilar", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CompareSimilar); }
        else if (id.Equals("NM1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel1); }
        else if (id.Equals("NM2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel2); }
        else if (id.Equals("NM3", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel3); }
        else if (id.Equals("NM4", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel4); }
        else if (id.Equals("NM5", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel5); }
        else if (id.Equals("NM6", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel6); }
        else if (id.Equals("NM7", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(NormalizePanel7); }
        else if (id.Equals("CP2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel2); }
        else if (id.Equals("CalculateGrowth", StringComparison.CurrentCultureIgnoreCase))
        { doCalc(sender, "Growth" ); }
        else if (id.Equals("CalculateDiff", StringComparison.CurrentCultureIgnoreCase))
        { doCalc(sender, "Diff" ); }
        else if (id.Equals("CalculatePercent", StringComparison.CurrentCultureIgnoreCase))
        { doCalc(sender, "Percent" ); }
        else if (id.Equals("CalculateRatio", StringComparison.CurrentCultureIgnoreCase))
        { doCalc(sender, "Ratio" ); }
        else if (id.Equals("CP6", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel6); }
        else if (id.Equals("CP5", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel5); }
        else if (id.Equals("CP1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel1); }
        else if (id.Equals("CP4", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel4); }
        else if (id.Equals("CP7", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel7); }
        else if (id.Equals("CP8", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel8); }
        else if (id.Equals("CP9", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(CalcPanel9); }
        else if (id.Equals("FP2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel2); }
        else if (id.Equals("FP3", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel3); }
        else if (id.Equals("FP4", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel4); }
        else if (id.Equals("FP5", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel5); }
        else if (id.Equals("FP6", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel6); }
        else if (id.Equals("FP1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(FilterPanel1); }
        else if (id.Equals("SM", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(SetMathPanel); }
        else if (id.Equals("TP3", StringComparison.CurrentCultureIgnoreCase))
        { doAddSelectedRowAsTrend(sender, e); }
        else if (id.Equals("TP1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(TestPanel1); }
        else if (id.Equals("TP2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(TestPanel2); }
        else if (id.Equals("BSort", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelSort); }
        else if (id.Equals("BReverseOrder", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelReverseOrder); }
        else if (id.Equals("bSwapCellsWithRows", StringComparison.CurrentCultureIgnoreCase))
        { swapCellValueHelper("Row", sender); }
        else if (id.Equals("bSwapCellsWithColumns", StringComparison.CurrentCultureIgnoreCase))
        { swapCellValueHelper("Column", sender); }
        else if (id.Equals("BSwapAxes", StringComparison.CurrentCultureIgnoreCase))
        { this.SwapAxes_Click(sender, e); }
        else if (id.Equals("btnMoveRow", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelMoveRow); }
        else if (id.Equals("btnMoveColumn", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelMoveColumn); }
        else if (id.Equals("BRowLabelToPages", StringComparison.CurrentCultureIgnoreCase))
        {
            string command = "moverowlabelstopages";
            doCommonPostback(command, sender);
        }
        else if (id.Equals("BTextColumnToPages", StringComparison.CurrentCultureIgnoreCase))
        {
            // The dialog for bPropertyValueToColumns is cloned for this
            findFocus(PanelTextColumnToPages);
        }
        else if (id.Equals("BColumnToPages", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelColumnToPages); }
        else if (id.Equals("BPropertyValueToColumns", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelPropertyValueToColumns); }
        else if (id.Equals("BSwapTextColumnAndRowLabel", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelSwapTextColumnAndRowLabel); }
        else if (id.Equals("BDeleteTextColumn", StringComparison.CurrentCultureIgnoreCase))
        {
            findFocus(PanelDeleteTextColumn);
        }
        else if (id.Equals("btnShowHidePages", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(ShowHidePagesDlg); }
        else if (id.Equals("btnHideAllPages", StringComparison.CurrentCultureIgnoreCase))
        {
            HidePagesExceptCurrent(sender, e);
        }
        else if (id.Equals("btnShowEventLogDlg", StringComparison.CurrentCultureIgnoreCase))
        {
            DoShowEventLogDlg();
        }
        else if (id.Equals("btnConvertAlertsToData", StringComparison.CurrentCultureIgnoreCase))
        {
            ConvertAlertsToData(sender, e);
        }
        else if (id.Equals("btnSelect", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(SelectDlg); }
        else if (id.Equals("btnRange", StringComparison.CurrentCultureIgnoreCase))
        { findFocus( PanelRangeSelect ); }

        else if (id.Equals("btnKeepSel", StringComparison.CurrentCultureIgnoreCase))
        { this.RemoveUnselected_Click(null, null); }
        else if (id.Equals("btnRemoveSel", StringComparison.CurrentCultureIgnoreCase))
        { this.RemoveSelected_Click(null, null); }
        else if (id.Equals("btnClearSel", StringComparison.CurrentCultureIgnoreCase))
        { DoClearAllSelection(null, null); }
        else if (id.Equals("InvertRows", StringComparison.CurrentCultureIgnoreCase))
        { doInvertRows(null, null); }
        else if (id.Equals("AP2", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AlertPanel2); }
        else if (id.Equals("AP3", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AlertPanel3); }
        else if (id.Equals("AP4", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AlertPanel4); }
        else if (id.Equals("AP1", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AlertPanel1); }
        else if (id.Equals("btnRename", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelRename); }
        else if (id.Equals("btnCellFormat", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelCellFormat); }
        else if (id.Equals("btnColumnFormat", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelColumnFormat); }
        else if (id.Equals("btnMacro", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PanelMacros); }
        else if (id.Equals("ChooseProject", StringComparison.CurrentCultureIgnoreCase))
        { SwitchToChooseProject(null, null); }
        else if (id.Equals("QuickView", StringComparison.CurrentCultureIgnoreCase))
        { SwitchToQuickView(null, null); }
        else if (id.Equals("btnPageCaptionEdit", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(PageCaptionEditPanel); }
        else if (id.Equals("AdminSaveAsProject", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminSaveAsProjectPanel); }
        else if (id.Equals("AdminSaveAsProjectForNod", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminSaveAsProjectPanelForNod); }
        else if (id.Equals("AdminSaveProjectScript", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminSaveProjectScriptPanel); }
        else if (id.Equals("AdminSavePageExported", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminSavePageExportedPanel); }
        else if (id.Equals("AdminAddData", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminAddDataPanel); }
        else if (id.Equals("AdminAddPage", StringComparison.CurrentCultureIgnoreCase))
        { findFocus(AdminAddPagePanel); }
        else if (id.Equals("RemoveCurrentPage", StringComparison.CurrentCultureIgnoreCase))
        { DoRemoveCurrentPage(sender); }
        else if (id.Equals("btnShowHideScript", StringComparison.CurrentCultureIgnoreCase))
        {
            populateProjectScriptBox(); // it wouldn't have been done when IsPostBack == false so this ensure it's done the first time.
            ScriptBox.Visible = !ScriptBox.Visible;
        }
    }

    protected void DoSaveChangesToProjectFile(object sender, EventArgs e)
    {
        doSaveChanges(ProjectScript.Text);
        SwitchToViewProject();
    }

    private bool doSaveChanges(string text)
    {
        try
        {
            string fullFileName = varParam.GetMyProjectsDir() + FilenameToSaveTo.Text;

            StreamWriter projectFile = new StreamWriter(fullFileName, false /* true means to append */ , System.Text.Encoding.Default);

            if (projectFile != null)
            {
                projectFile.Write(text);

                projectFile.Close();
                ViewState["InteractiveUpdates"] = null;                
            }
            return true;
        }
        catch (System.UnauthorizedAccessException)
        {
        }
        catch (System.AccessViolationException)
        {
            // todo: security violation... e.g. access is denied..
        }
        catch (IOException)
        {
        }
        catch (System.ArgumentException)
        {
        }
        return false;
    }

    protected void DoShowEventLogDlg(object sender, EventArgs e)
    {
        DoShowEventLogDlg();
    }

    void DoShowEventLogDlg()
    {
        string output = varParam.ShowLogFile();
        if (output != null)
        {
            EventLogZone.InnerHtml = output;
        }
        else
            EventLogZone.InnerHtml = "";

        findFocus(ShowEventLogDlg);
    }

    void populateProjectScriptBox()
    {
        string fileName = varParam.GetMyProjectsDir() + FilenameToSaveTo.Text;
        if (System.IO.File.Exists(fileName) == false)
        {
            ProjectScript.Text = "Requested Project Is Missing - " + FilenameToSaveTo.Text;
        }
        else
        {
            ProjectScript.Text = "";
            String mostRecentCommand = "";

            string[] lines = System.IO.File.ReadAllLines(fileName);
            foreach (string s in lines)
            {
                mostRecentCommand = s;
                ProjectScript.Text += (s + System.Environment.NewLine);
            }
            ProjectScript.Text += (SaveNotificationComment) ;

            List<String> strings = (List<String>)ViewState["InteractiveUpdates"];
            if (strings != null)
            {
                for (int i = 0, count = strings.Count; i < count; i++)
                {
                    string s = strings[i];
                    mostRecentCommand = s;
                    ProjectScript.Text += (s + System.Environment.NewLine);
                }

                this.Title = String.Format( "{0} command{1} unsaved", strings.Count, strings.Count == 1 ? "" : "s" );
            }
            else
                this.Title = String.Format("Author Mode - {0}", fileName);

            if (mostRecentCommand.Length > 0)
            {
                String[] tokens = mostRecentCommand.Split(',');
                if (tokens.Length > 0)
                {
                    GoogleSearchWords.Text = tokens[0];
                    DoGoogleSearch( null, null);
                }
            }
        }

        ProjectScript.Font.Name = "Courier New";
        ProjectScript.Font.Size = FontUnit.Small;

    }

    protected void DoGoogleSearch( object sender, EventArgs e )
    {
        if (GoogleSearchWords.Text.Length > 0)
        {
            GoogleResults.Visible = true;
            String strToSearchFor = "http://www.google.com/search?hl=en&q=nextanalytics.com+" 
                + HttpUtility.UrlEncode( GoogleSearchWords.Text );
            GoogleResults.Attributes["src"] = strToSearchFor;
        }
        else
            GoogleResults.Visible = false;
    }

    protected void closeAllDlgs(object sender, EventArgs e)
    {
        closeAllDlgs();
    }

    private void closeAllDlgs()
    {
        // ShowEventLogDlg is purposely NOT in this list

        Panel[] deselectedPanel = { 
         ShowAsPanel1,         ShowAsPanel2,         ShowAsPanel3,         ShowAsPanel4,         ShowAsPanel5, CompareSimilar,
         NormalizePanel1,         NormalizePanel2,         NormalizePanel3,         NormalizePanel4,         
            NormalizePanel5,         NormalizePanel6,         NormalizePanel7,
         CalcPanel1,         CalcPanel2,         CalcPanel4,         CalcPanel5,         CalcPanel6,         CalcPanel7, CalcPanel8, CalcPanel9,
         SetMathPanel, FilterPanel1,         FilterPanel2,         FilterPanel3,         FilterPanel4,         FilterPanel5,         FilterPanel6,
         PanelMacros,         PanelRename,         PanelCellFormat, PanelColumnFormat,         
            ShowHidePagesDlg, ShowEventLogDlg, SelectDlg,PanelRangeSelect, PanelSort,         PanelReverseOrder,         PanelMoveRow,         PanelMoveColumn,         
            PanelColumnToPages,         PanelPropertyValueToColumns,         PanelTextColumnToPages,
            PanelSwapAxes, PanelSwapCellsWithColumns, PanelSwapCellsWithRows, PanelSwapTextColumnAndRowLabel, PanelDeleteTextColumn,
         AlertPanel1,         AlertPanel2,         AlertPanel3,         AlertPanel4,         
         TestPanel1,         TestPanel2,         TestPanel3,
        PageCaptionEditPanel, AdminSavePageExportedPanel, AdminAddDataPanel, AdminSaveProjectScriptPanel, 
            AdminAddPagePanel, AdminSaveAsProjectPanel,  AdminSaveAsProjectPanelForNod };

        foreach (Panel desel in deselectedPanel)
        {
            desel.Attributes["class"] = "";
            desel.Visible = false;
        }

        // MyControls.Visible = true;

    }

    private void setStandardControlStyle(System.Web.UI.WebControls.DropDownList thisList)
    {
        thisList.Items.Clear();
    }

    private string myPageCaption(Data.Page thisPage)
    {
        string caption = thisPage.GetPageCaption();

        return caption;
    }

    private void loadPageControls(Data.Page currentPage)
    {
        if (currentPage != null)
        {
            System.Web.UI.WebControls.DropDownList[] pageControls = {
                    ChangeSelectedPage,                    
                    AllPages,
                    AxisShowAsAxisPctPageIndex,
                    AxisShowAsRelativeCellPageIndex,
                    AxisShowAsAbsolutePositionPageIndex,
                    AxisShowAsToARowPageIndex,
                    AxisShowAsPctToAColumnPageIndex,
                    DistributionPageToImitateIndex,
                    FilterByCaptionFromAnotherPagePageIndex,
                    MoveRowsPages,
                    MoveColumnsPages,
                    AlertCompareToAnotherCellPages,
                    AlertCompareToAxisPages,
                    AlertUsingCellValuesPages,
                    SetMathPage1, SetMathPage2
                    };

            int selPageIndex = currentPage.GetIndex();

            string pageCaption = myPageCaption(currentPage);

            pageCaption = pageCaption.Replace(">", "&gt;");
            pageCaption = pageCaption.Replace("<", "&lt;");

            pageCaption = dc.ReplacePromptValues(pageCaption);

            UnselectablePageCaption.Text = pageCaption;
            UnselectablePageCaption.Visible = true;

            MenuItem mainMenuItem = new MenuItem(pageCaption, "doShowRenamePageCaption");
            mainMenuItem.Selectable = false;
            
            foreach (System.Web.UI.WebControls.DropDownList thisList in pageControls)
            {
                setStandardControlStyle(thisList);
            }


            for (int pageIndex = 0, pageCount = currentData.GetPageCount(); pageIndex < pageCount; pageIndex++)
            {
                Data.Page thisPage = currentData.GetPage( pageIndex );

                bool endUserSelectable = thisPage.Visible();

                string caption = thisPage.GetPageCaption();
                if (endUserSelectable == false)
                    caption += " (hidden from normal view)";

                foreach (System.Web.UI.WebControls.DropDownList thisList in pageControls)
                {
                    ListItem listItem = new ListItem(caption, thisPage.GetIndex().ToString());

                    if (DistributionPageToImitateIndex == thisList  // can't distribute to the same page
                        || FilterByCaptionFromAnotherPagePageIndex == thisList  // doesn't make sense to filter from captions on the same page
                        )
                    {
                        if (pageIndex != selPageIndex)
                            thisList.Items.Add(listItem);
                    }
                    else if (ChangeSelectedPage == thisList)
                    {
                        if (endUserSelectable)
                        {
                            string newText;
                            if (lh.GetUserCanSave())
                                newText = "Page # " + pageIndex.ToString() + " : " + listItem.Text;
                            else
                                newText = listItem.Text;

                            listItem.Text = newText;

                            thisList.Items.Add(listItem);

                            if (pageIndex == selPageIndex)
                            {
                                listItem.Selected = true;
                                if (thisList.Items.Count > pageIndex)  // this shouldn't be possible except we might be reading a fi
                                    thisList.SelectedIndex = pageIndex;
                            }
                        }
                    }
                    else
                    {
                        thisList.Items.Add(listItem);
                    }
                }


            }
            System.Web.UI.WebControls.DropDownList[] pageControlsThatNeedNewPage = {
                    MoveRowsPages,
                    MoveColumnsPages

            };
            foreach (System.Web.UI.WebControls.DropDownList thisList in pageControlsThatNeedNewPage)
            {
                thisList.Items.Add(new ListItem("New Page", "-1"));
            }

            System.Web.UI.WebControls.DropDownList[] pageControlsThatNeedSamePage = {
                    AlertCompareToAnotherCellPages,
                    AlertCompareToAxisPages,
                    AlertUsingCellValuesPages

            };
            foreach (System.Web.UI.WebControls.DropDownList thisList in pageControlsThatNeedSamePage)
            {
                thisList.Items.Add(new ListItem("Same Page (moves with each page that's added)", "-1"));
            }

            foreach (System.Web.UI.WebControls.DropDownList thisList in pageControls)
            {
                if (ChangeSelectedPage != thisList)
                {
                    thisList.ClearSelection();
                    if (DistributionPageToImitateIndex == thisList
                        || FilterByCaptionFromAnotherPagePageIndex == thisList
                        )
                    {
                    }
                    else if (AlertCompareToAnotherCellPages == thisList
                        || AlertCompareToAxisPages == thisList
                        || AlertUsingCellValuesPages == thisList)
                    {
                        thisList.SelectedIndex = thisList.Items.Count - 1;// want this to be the "last one" the one with "Same Page..."
                    }
                    else
                    {
                        thisList.SelectedIndex = selPageIndex;
                    }
                }
            }
        }
    }

    private void LoadControlsThatNeedFreshData(Data.Page currentPage)
    {
        /* this ensures that, for example, if there was a new page added to the Data Class, 
         * Page controls contain the addition.  Or, if the Alert parameters changed, the Control 
         * which displays what Alert params are in effect, the Control gets the fresh info. 
         */
        const int REASONABLE_MAX_FOR_ASPNET_CONTROL = 1000; // if I swapped 35,000 rows to columns asp.net would have an error with the page after it rendered i.e. couldn't do anything else with it "server error".  probably exceed some internal limit, specially since there are several columns controls all taking 35,000 duplicate text strings

        if (currentPage != null)
        {
            PageCaptionNew.Text = currentPage.GetPageCaption();
            PageDescriptionNew.Text = currentPage.GetPageDescription();

            // load the controls which change as a result of data

            loadPageControls(currentPage);
        }

        System.Web.UI.WebControls.DropDownList[] baselineControls = { BaselineId, BaselineIdR };
        foreach (System.Web.UI.WebControls.DropDownList thisList in baselineControls)
        {
            setStandardControlStyle(thisList);
        }
        if (dc != null)
        {
            for (int i = 0, count = dc.GetBaselineCount(); i < count; i++)
            {
                foreach (System.Web.UI.WebControls.DropDownList thisList in baselineControls)
                {
                    thisList.Items.Add( dc.GetBaselineId( i  ) );
                }
            }
        }

        System.Web.UI.WebControls.DropDownList[] columnsControls = {
            SortColumns,
            AxisFilterValueColumns,
            FilterValueColumns,
            MoveColumnToPagesColumns
        };

        foreach (System.Web.UI.WebControls.DropDownList thisList in columnsControls)
        {
            setStandardControlStyle(thisList);
        }

        int selColumnIndex = -1;

        if (currentPage != null)
        {
            if (selColumnIndex == -1)
            {
                selColumnIndex = currentPage.GetNumericColumnCount() - 1;
            }

            for (int colIndex = 0, colCount = currentPage.GetNumericColumnCount(); 
                            colIndex < colCount && colIndex < REASONABLE_MAX_FOR_ASPNET_CONTROL; colIndex++)
            {
                string caption = currentPage.GetNumericColumnName(colIndex);
                foreach (System.Web.UI.WebControls.DropDownList thisList in columnsControls)
                {
                    ListItem li = new ListItem(caption, caption);
                    thisList.Items.Add(li);
                    if (selColumnIndex == colIndex)
                        thisList.SelectedIndex = colIndex;
                }
            }
        }

        AxisFilterValueColumns.Items.Add(new ListItem("All Columns", "*"));
        FilterValueColumns.Items.Add(new ListItem("All Columns", "*"));

        System.Web.UI.WebControls.ListBox[] columnsControlsListBox = {
            AssignColumnFormatColumns, PanelCellFormatListbox };

        foreach (System.Web.UI.WebControls.ListBox thisList in columnsControlsListBox)
        {
            thisList.Items.Clear();
        }

        if (currentPage != null)
        {
            for (int colIndex = 0, colCount = currentPage.GetNumericColumnCount(); colIndex < colCount && colIndex < REASONABLE_MAX_FOR_ASPNET_CONTROL; colIndex++)
            {
                string caption = currentPage.GetNumericColumnName(colIndex);
                foreach (System.Web.UI.WebControls.ListBox thisList in columnsControlsListBox)
                {
                    ListItem li = new ListItem(caption, caption);
                    thisList.Items.Add(li);
                    if (currentPage.GetSelectedPosition( "column", colIndex) )
                        li.Selected = true;
                }
            }
        }

        FilterByCaptionFromAPropertyIndex.Items.Clear();
        SwapTextColumnWithColumnPropertyIndex.Items.Clear();
        SwapTextColumnWithColumnPropertyIndex2.Items.Clear();
        SwapTextColumnWithColumnPropertyIndex3.Items.Clear();
        SwapTextColumnRowLabelPropertyIndex.Items.Clear();
        CombineByTextTextIndex.Items.Clear();
        CompareByTextTextIndex.Items.Clear();
        FindTextTextColumnNames.Items.Clear();

        if (currentPage != null)
        {
            for (int propIndex = 0, propCount = currentPage.GetAllTextColumnCount(); propIndex < propCount; propIndex++)
            {
                string caption = currentPage.GetAllTextColumnName(propIndex);
                ListItem li = new ListItem(caption, propIndex.ToString());
                FilterByCaptionFromAPropertyIndex.Items.Add(li);
                SwapTextColumnWithColumnPropertyIndex.Items.Add(li);
                SwapTextColumnRowLabelPropertyIndex.Items.Add(li);
                CombineByTextTextIndex.Items.Add(new ListItem(caption, propIndex.ToString()));
                CompareByTextTextIndex.Items.Add(new ListItem(caption, caption));
                FindTextTextColumnNames.Items.Add(new ListItem(caption, propIndex.ToString()));

                // the following one supply the text column caption not the index
                SortColumns.Items.Add(new ListItem(caption, "SortTextColumn" + MyVariables.DelimForTokens + caption));
                SwapTextColumnWithColumnPropertyIndex2.Items.Add(new ListItem(caption, caption));
                SwapTextColumnWithColumnPropertyIndex3.Items.Add(new ListItem(caption, caption));
            }
            int threshold = currentPage.GetNumericColumnCount() / 2;
            BaselineThresholdCount.Text = BaselineThresholdCountR.Text = threshold.ToString();    // default to half the columns...

            string rowLabelName = currentPage.ccs.GetRowLabelName();

            ListItem rowLabel = new ListItem(rowLabelName, "-1");
            FindTextTextColumnNames.Items.Insert(0, rowLabel);
            CombineByTextTextIndex.Items.Insert(0, rowLabel);
            CompareByTextTextIndex.Items.Insert(0, new ListItem(rowLabelName, rowLabelName));

            SortColumns.Items.Add(new ListItem(rowLabelName, "SortRowLabel"));

            // CombineByTextTextIndex.Items.Insert(0, new ListItem( "All Text Must Match", "-2" )); I think this is an artifact from before days of combineduplicate

        }

        /* script files don't change that often, so this next section could probably 
         * be in the static section. But it is kept here as a niceness to open sessions
         * to see the newly added scripts in near-real-time */
        string scriptDirectory = varParam.GetMyScriptsDir();
        string[] files = System.IO.Directory.GetFiles(scriptDirectory);
        ScriptFiles.Items.Clear();
        foreach (string s in files)
        {
            ListItem li = new ListItem();
            int indexOfLastSlash = s.LastIndexOf(@"\");
            if (indexOfLastSlash == -1)
                indexOfLastSlash = 0;
            else
                indexOfLastSlash++; // skip the slash itself, we don't need to see it.

            string shortFileName = s.Substring(indexOfLastSlash);
            li.Text = shortFileName;
            li.Value = shortFileName;
            ScriptFiles.Items.Add(li);
        }


        string dataDirectory = varParam.GetMyDataDir();
        files = System.IO.Directory.GetFiles(dataDirectory);
        ListofFilesInImportedDataDir.Items.Clear();
        AddDataFileNames.Items.Clear();
        foreach (string s in files)
        {
            ListItem li = new ListItem();
            int indexOfLastSlash = s.LastIndexOf(@"\");
            if (indexOfLastSlash == -1)
                indexOfLastSlash = 0;
            else
                indexOfLastSlash++; // skip the slash itself, we don't need to see it.

            string shortFileName = s.Substring(indexOfLastSlash);
            li.Text = shortFileName;
            li.Value = shortFileName;
            ListofFilesInImportedDataDir.Items.Add(li);
            AddDataFileNames.Items.Add(li);
        }


        string projectsDirectory = varParam.GetMyProjectsDir();
        files = System.IO.Directory.GetFiles(projectsDirectory);
        AdminSaveAsProjectListBox.Items.Clear();
        foreach (string s in files)
        {
            ListItem li = new ListItem();
            int indexOfLastSlash = s.LastIndexOf(@"\");
            if (indexOfLastSlash == -1)
                indexOfLastSlash = 0;
            else
                indexOfLastSlash++; // skip the slash itself, we don't need to see it.

            string shortFileName = s.Substring(indexOfLastSlash);
            li.Text = shortFileName;
            li.Value = shortFileName;
            AdminSaveAsProjectListBox.Items.Add(li);
        }

        bool anyColumnSelected = false;
        bool oneColumnSelected = false;
        bool oneRowSelected = false;
        if (currentPage != null)
        {
            double val = currentPage.GetSelectedCellValue();
            if (val != Data.Data.BadNum())
            {
                FilterValueToCompareTo.Text = val.ToString();  //n.b. intentionally unformatted
            }
            anyColumnSelected = currentPage.AnySelected("column");
            oneColumnSelected = currentPage.GetSelectedCount("column") == 1;
            oneRowSelected = currentPage.GetSelectedCount("row") == 1;

            int index = currentPage.GetFirstSelected("row");
            if( index != -1 )
                SelectRangeStart.Text = index.ToString();

            if (oneColumnSelected)
            {
                int columnIndex = currentPage.GetFirstSelected("column");
                if (columnIndex != -1)
                {
                    string caption = currentPage.GetNumericColumnName(columnIndex);
                    RenameLabelsOldColumnCaption.Text = caption;
                }
            }
            else if (oneRowSelected)
            {
                int rowIndex = currentPage.GetFirstSelected("row");
                if (rowIndex != -1)
                {
                    string caption = currentPage.GetRowLabelName();
                    RenameLabelsOldColumnCaption.Text = caption;
                }
            }
        }
    }

    protected void DoReloadUIControls(object sender, EventArgs e)
    {
        Data.Page currentPage = currentData.GetSelectedPage();
        LoadControlsThatNeedFreshData(currentPage);
    }

    public void getHTMLCrosstabTable(Data.Page thisPage, Data.VarParams varParam, bool justTheControls, HtmlTable crosstab)
    {
        string cellId = "";
        string cssClass = "";
        string selectionState = "";
        string innerText = "";

        crosstab.Rows.Clear();

        HtmlTableCell thisCell;

        // remaining crosstab

        HtmlTableRow headerRow = new HtmlTableRow();
        innerText = thisPage.ccs.GetRowLabelName();
        selectionState = "f";
        cellId = "RowlabelTD" + MyVariables.DelimForTokens + "true";
        string command = "sortrowlabel" + MyVariables.DelimForTokens + "true";
        thisCell = resultableTDForScript(cellId, command, "RowLabelCaption", selectionState, innerText);
        if (thisCell != null)
            headerRow.Controls.Add(thisCell);

        // text column headers
        for (int i = 0, count = thisPage.GetTextColumnCount(); i < count; i++)
        {
            string propertyName = thisPage.GetTextColumnName(i);
            cellId = "TextColumn" + MyVariables.DelimForTokens + propertyName + MyVariables.DelimForTokens + "true";
            command = "sorttextcolumn" + MyVariables.DelimForTokens + propertyName + MyVariables.DelimForTokens + "true";
            thisCell = resultableTDForScript(cellId, command, "TextColumnCaption", "f", propertyName);
            if (thisCell != null)
            {
                headerRow.Controls.Add(thisCell); // todo: if they can indicate that this column is selected, then put in a balloon to filter by *this* caption/text column
            }
        }

        // the column headers
        int colCount = thisPage.GetNumericColumnCount();

        for ( int colIndex = 0; colIndex < colCount; colIndex++)
        {
            string colCaption = thisPage.GetNumericColumnName(colIndex);
            innerText = colCaption;
            cellId = thisPage.GetColUID(colIndex);
            if (thisPage.GetSelectedPosition( "column",  colIndex))
            {
#if WANT_SVG_EMBED
					string embedCommand = 
								@"<embed wmode='transparent' src='" 
								+ varParam.getSVGFileForTwoLineCallout()
								+ "' height='60' width='100' type='image/svg+xml' line1='Click to' line2='Sort' cmd='SortThisColumn;" + colIndex + "' />";

					innerText += embedCommand;
#endif
                cssClass = "Selected";
                selectionState = "t";
            }
            else
            {
                cssClass = "ColCaption";
                selectionState = "f";
            }
            thisCell = appendColumnCaptionTD(cellId, cssClass, selectionState, innerText, thisPage, colIndex);
            if (thisCell != null)
                headerRow.Controls.Add(thisCell);

        }
        crosstab.Rows.Add(headerRow); // end of header row

        int actualRowCount = thisPage.GetRowCount();
        int maxTableRows = GetMaxTableRows();

        for (int i = GetRowThumb( thisPage ), rowCounter = 0; 
                i < actualRowCount && rowCounter < maxTableRows; 
                i++, rowCounter++)
        {
            int colIndex = 0;
            makeTableRow( i, crosstab, thisPage, colIndex, justTheControls, colCount);
        }
    }

    private int GetMaxTableRows()
    {
        try
        {
            int maxTableRows = Convert.ToInt32(RowCount.Text);
            return maxTableRows;
        }
        catch (System.FormatException) { return 0; }
    }
    private int GetRowThumb( Data.Page currentPage )
    {
        if (RowThumb.Text.Length == 0)
            return 0;

        try
        {
            int thumbStart = Convert.ToInt32( RowThumb.Text );
            return thumbStart;
        }
        catch (System.FormatException) {
            if (currentPage != null && RowThumb.Text.Length != 0 )
            {
                String compareText = RowThumb.Text;
                for (int rowIndex = 0, rowCount = currentPage.GetRowCount();
                        rowIndex < rowCount; rowIndex++)
                {
                    String rowLabel = currentPage.GetRowLabelValue(rowIndex);
                    if (rowLabel.StartsWith( compareText , StringComparison.CurrentCultureIgnoreCase))
                        return rowIndex;
                }
            }
            return 0;
        }
    }

    private void makeTableRow(int rowIndex, HtmlTable crosstab, Data.Page thisPage, int colIndex2, bool justTheControls, int colCount)
    {
        bool isRowSelected = thisPage.GetSelectedPosition( "row",  rowIndex );
        HtmlTableRow tableRow = new HtmlTableRow();
        crosstab.Rows.Add(tableRow);

        // row-label
        string rowLabel = thisPage.GetRowLabelValue(rowIndex);
        string innerText = rowLabel;
        string cellId = thisPage.GetRowUID(rowIndex);
        string cssClass;
        string selectionState;

        if (isRowSelected)
        {
            cssClass = "Selected";
            selectionState = "t";
#if WANT_SVG_EMBED
					if( thisPage.ccs.getSelectedRowCount() == 1 )
					{
						string embedCommand = @"<embed wmode='transparent' src='"
						+ varParam.getSVGFileForTwoLineCallout()
						+ "' height='60' width='100' type='image/svg+xml' line1='Sum' line2='The Rest' cmd='SumTheRest;" + rowIndex + "' />";
						innerText += embedCommand;
					}
					else if( bAlreadyPromptedForSumSelected == false )
					{
						bAlreadyPromptedForSumSelected = true;
						string embedCommand = @"<embed wmode='transparent' src='" 
						+ varParam.getSVGFileForTwoLineCallout()
						+ "' height='60' width='100' type='image/svg+xml' line1='Sum' line2='Selected' cmd='SumSelected;" + rowIndex + "' />";
						innerText += embedCommand;
					}
#endif
        }
        else
        {
            cssClass = "RowLabel";
            selectionState = "f";
        }
        HtmlTableCell thisCell = appendRowLabelTD(cellId, cssClass, selectionState, innerText, thisPage, rowIndex);
        if (thisCell != null)
            tableRow.Controls.Add(thisCell);

        // text column values (on each row)
        for (int i = 0, count = thisPage.GetTextColumnCount(); i < count; i++)
        {
            string textColumnName = thisPage.GetTextColumnName(i);
            innerText = thisPage.GetTextColumnValue(rowIndex, i);

            /* we're now in the textcolumn cell.  We could put a hyperlink to do one thing, or we could put a couple of teensy little hyperlinks
             * as kind of a minitoolbar. They'd want a show/hide to this capability.  SearchAndSelect,Contains,0,Wednesday
             * 
             * The same applies for the caption (at the top of the column), it doesn't need to be sort-desc, it could easily be aggregatebyuniquetext.
             */
            string uniqueCellId = rowIndex + MyVariables.DelimForTokens + textColumnName + innerText;
            string command = "SearchAndSelect" + MyVariables.DelimForTokens + "ExactMatch" 
                + MyVariables.DelimForTokens + i + MyVariables.DelimForTokens 
                + innerText;

            if (isRowSelected)
            {
                cssClass = "Selected";
                selectionState = "t";
            }
            else
            {
                cssClass = "TextColumn";
                selectionState = "t";
            }

            thisCell = resultableTDForScript(uniqueCellId, command, cssClass, selectionState, innerText);

            if (thisCell != null)
                tableRow.Controls.Add(thisCell);
        }

        // the cells
        int colIndex = colIndex2;
        for (; colIndex < colCount; colIndex++)
        {
            cellId = thisPage.GetCellUID(rowIndex, colIndex);

            if (justTheControls == false)
            {
                if (thisPage.GetSelectedPosition( "Column", colIndex) && thisPage.GetSelectedPosition( "row", rowIndex) )
                {
                    cssClass = "Selected";
                    selectionState = "t";
                }
                else
                {
                    cssClass = thisPage.GetCssClass(rowIndex, colIndex);
                    selectionState = "f";
                }
                innerText = thisPage.GetNumericCellContents(rowIndex, colIndex, true);
            }
            else
            {
                selectionState = "f";
                cssClass = "";
                innerText = thisPage.GetNumericCellContents(rowIndex, colIndex,true );
            }

            thisCell = appendCellTD(cellId, cssClass, selectionState, innerText, thisPage, rowIndex, colIndex);
            if (thisCell != null)
            {
                tableRow.Controls.Add(thisCell);
            }
        }
    }

    private void makeChart(bool justTheControls)
    {
        CurrentPageCrosstab.Rows.Clear();

        if (currentData == null)
            return;

        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
            makeChart(currentPage, justTheControls);

    }

    private void makeChart(Data.Page currentPage, bool justTheControls)
    {
        getHTMLCrosstabTable( currentPage, varParam, justTheControls, CurrentPageCrosstab);

        if (justTheControls == false)
        {
            string pageText = currentPage.GetPageDescription();
            if (pageText.Length > 0)
            {
                pageText = pageText.Replace(">", "&gt;");
                pageText = pageText.Replace("<", "&lt;");
                pageText = dc.ReplacePromptValues(pageText);

                PageDescription.Text = pageText;
                PageDescription.Visible = true;
            }
            else
                PageDescription.Visible = false;
        }
    }

    protected void DoHidePage(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            try
            {
                int index = Convert.ToInt16(AllPages.SelectedValue);
                if (index != -1)
                {
                    currentData.SetSelectedPage( index, true );
                    Data.Page currentPage = currentData.GetSelectedPage();
                    if (currentPage != null)
                    {
                        string cmd;
                        if (currentPage.Visible())
                            cmd = "HidePage";
                        else
                            cmd = "ShowPage";

                        cmd += MyVariables.DelimForTokens + index;

                        doCommonPostback(cmd, sender);

                        //Data.Page currentPage = currentData.GetSelectedPage();
                        //loadPageControls(currentPage);
                    }

                }
            }
            catch (System.FormatException) { }
        }
    }

    protected void DoRemovePage(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            try
            {
                int index = Convert.ToInt16(AllPages.SelectedValue);
                if (index != -1)
                {
                    currentData.SetSelectedPage(index, true);
                    string cmd = "RemovePage" + MyVariables.DelimForTokens + index;
                    doCommonPostback(cmd, sender);

                    Data.Page currentPage = currentData.GetSelectedPage();
                    loadPageControls(currentPage);

                }
            }
            catch (System.FormatException) { }
        }
    }
    protected void DoChangePage(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            try
            {
                int index = Convert.ToInt16(AllPages.SelectedValue);
                if (index != -1)
                {
                    string cmd = "Select" + MyVariables.DelimForTokens + "Page" + MyVariables.DelimForTokens + index;
                    doCommonPostback(cmd, sender);
                }
            }
            catch (System.FormatException) { }
        }
    }
    protected void DoRowFind(object sender, EventArgs e)
    {
        ImageButton btn = (ImageButton)sender;
        string arg = btn.CommandArgument;

        string index = FindTextTextColumnNames.SelectedValue;

        string cmd = "SearchAndSelect" + MyVariables.DelimForTokens
            + arg + MyVariables.DelimForTokens
            + index + MyVariables.DelimForTokens
            + FindText.Text;  // todo: -1 means search rowLabel, anything higher should be the propertyIndex
        doCommonPostback(cmd, sender);
    }

    protected void DoRowFind2(object sender, EventArgs e)
    {
        string index = FindTextTextColumnNames.SelectedValue;
        string arg = FindTextTextColumnOperator.SelectedValue;

        string cmd = "SearchAndSelect" + MyVariables.DelimForTokens
            + arg + MyVariables.DelimForTokens
            + index + MyVariables.DelimForTokens
            + FindText.Text;  // todo: -1 means search rowLabel, anything higher should be the propertyIndex
        doCommonPostback(cmd, sender);
    }

    protected void DoScrollHome(object sender, EventArgs e)
    {
        string cmd = "ScrollHome";
        doCommonPostback(cmd, sender);
    }
    protected void DoScrollBottom(object sender, EventArgs e)
    {
        string cmd = "ScrollBottom";
        doCommonPostback(cmd, sender);
    }

    protected void DoScrollLeftMost(object sender, EventArgs e)
    {
        string cmd = "ScrollLeftMost";
        doCommonPostback(cmd, sender);
    }

    protected void DoScrollRightMost(object sender, EventArgs e)
    {
        string cmd = "ScrollRightMost";
        doCommonPostback(cmd, sender);
    }

    protected void DoScrollDown(object sender, EventArgs e) { string cmd = "ScrollDown"; doCommonPostback(cmd, sender); }
    protected void DoScrollPageDown(object sender, EventArgs e) { string cmd = "ScrollPageDown"; doCommonPostback(cmd, sender); }
    protected void DoScrollUp(object sender, EventArgs e) { string cmd = "ScrollUp"; doCommonPostback(cmd, sender); }
    protected void DoScrollPageUp(object sender, EventArgs e) { string cmd = "ScrollPageUp"; doCommonPostback(cmd, sender); }
    protected void DoScrollLeft(object sender, EventArgs e) { string cmd = "ScrollLeft"; doCommonPostback(cmd, sender); }
    protected void DoScrollPageLeft(object sender, EventArgs e) { string cmd = "ScrollPageLeft"; doCommonPostback(cmd, sender); }
    protected void DoScrollRight(object sender, EventArgs e) { string cmd = "ScrollRight"; doCommonPostback(cmd, sender); }
    protected void DoScrollPageRight(object sender, EventArgs e) { string cmd = "ScrollPageRight"; doCommonPostback(cmd, sender); }

    protected void CompareByText_Click(object sender, EventArgs e)
    {
        string cmd = "comparesimilar" + MyVariables.DelimForTokens
            + CompareByTextTextIndex.SelectedValue + MyVariables.DelimForTokens
            + CompareByTextAggregation.SelectedValue;
        doCommonPostback(cmd, sender);
    }


    protected void AggregationByText_Click(object sender, EventArgs e)
    {
        string cmd = "combinesimilarbyindex" + MyVariables.DelimForTokens
            + CombineByTextTextIndex.SelectedValue + MyVariables.DelimForTokens
            + CombineByTextAggregation.SelectedValue;
        doCommonPostback(cmd, sender);
    }

    protected void CombineDuplicates_Click(object sender, EventArgs e)
    {
        string cmd = "combineduplicates" + MyVariables.DelimForTokens + CombineDuplicatesAggregation.SelectedValue;
        doCommonPostback(cmd, sender);
    }

    protected void ShowAsToAxisPct_Click(object sender, EventArgs e)
    {
        string agg = AggregationShowAsPctAxis.Text;
        string axis = AxisShowAsPctAxis.Text;
        string comparisonType = AxisShowAsAxisPctComparisonType.Text;
        string pageIndex = AxisShowAsAxisPctPageIndex.SelectedValue;
        string rowIndex = "-1";
        string columnIndex = "-1";
        string rowCaption = "";
        string columnCaption = "";
        string rowLag = "0";
        string columnLag = "0";
        string useRowCaption = "False";
        string useColumnCaption = "False";
        string cmd = "Compare" + MyVariables.DelimForTokens
            + "ToAxis" + MyVariables.DelimForTokens
            + comparisonType + MyVariables.DelimForTokens
            + agg + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens
            + rowCaption + MyVariables.DelimForTokens
            + columnCaption + MyVariables.DelimForTokens
            + rowIndex + MyVariables.DelimForTokens
            + columnIndex + MyVariables.DelimForTokens
            + rowLag + MyVariables.DelimForTokens
            + columnLag + MyVariables.DelimForTokens
            + useRowCaption + MyVariables.DelimForTokens
            + useColumnCaption + MyVariables.DelimForTokens
            + pageIndex + MyVariables.DelimForTokens
            ;

        doCommonPostback(cmd, sender);

    }
    protected void ShowAsToRelativeCellPct_Click(object sender, EventArgs e)
    {
        string agg = "Actual"; // unused
        string axis = "Row"; // unused
        string comparisonType = AxisShowAsRelativeCellComparisonType.Text;
        string pageIndex = AxisShowAsRelativeCellPageIndex.SelectedValue;
        string rowIndex = "-1";
        string columnIndex = "-1";
        string rowCaption = "";
        string columnCaption = "";
        string rowLag = AxisShowAsRelativeCellRowLag.Text;
        string columnLag = AxisShowAsRelativeCellColumnLag.Text;
        string useRowCaption = "False";
        string useColumnCaption = "False";
        string cmd = "Compare" + MyVariables.DelimForTokens
            + "ToRelativeCell" + MyVariables.DelimForTokens
            + comparisonType + MyVariables.DelimForTokens
            + agg + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens
            + rowCaption + MyVariables.DelimForTokens
            + columnCaption + MyVariables.DelimForTokens
            + rowIndex + MyVariables.DelimForTokens
            + columnIndex + MyVariables.DelimForTokens
            + rowLag + MyVariables.DelimForTokens
            + columnLag + MyVariables.DelimForTokens
            + useRowCaption + MyVariables.DelimForTokens
            + useColumnCaption + MyVariables.DelimForTokens
            + pageIndex + MyVariables.DelimForTokens;

        doCommonPostback(cmd, sender);

    }
    protected void btnShowAsPctAbsolutePosition_Click(object sender, EventArgs e)
    {
        string agg = "Actual"; // unused
        string axis = "Row"; // unused
        string comparisonType = AxisShowAsAbsolutePositionComparisonType.Text;

        string rowCaption = AxisShowAsAbsolutePositionRowIndex.Text;
        string columnCaption = AxisShowAsAbsolutePositionColumnIndex.Text;

        string pageIndex = AxisShowAsAbsolutePositionPageIndex.SelectedValue;

        string rowIndex = AxisShowAsAbsolutePositionRowIndex.Text;
        string columnIndex = AxisShowAsAbsolutePositionColumnIndex.Text;
        string rowLag = "0";
        string columnLag = "0";

        string useRowCaption;
        if (rowIndex.Contains("#"))
            useRowCaption = "False";
        else
            useRowCaption = "True";

        string useColumnCaption;
        if (columnIndex.Contains("#"))
            useColumnCaption = "False";
        else
            useColumnCaption = "True";

        string serverCommand = "Compare" + MyVariables.DelimForTokens
                                + "AbsolutePosition" + MyVariables.DelimForTokens
                                + comparisonType + MyVariables.DelimForTokens
                    + agg + MyVariables.DelimForTokens
                    + axis + MyVariables.DelimForTokens
                    + rowCaption + MyVariables.DelimForTokens
                    + columnCaption + MyVariables.DelimForTokens
                    + rowIndex + MyVariables.DelimForTokens
                    + columnIndex + MyVariables.DelimForTokens
                    + rowLag + MyVariables.DelimForTokens
                    + columnLag + MyVariables.DelimForTokens
                    + useRowCaption + MyVariables.DelimForTokens
            + useColumnCaption + MyVariables.DelimForTokens
            + pageIndex + MyVariables.DelimForTokens;

        this.doCommonPostback(serverCommand, sender);
    }

    protected void btnShowAsSpecificRow_Click(object sender, EventArgs e)
    {
        string agg = "Actual"; // unused
        string axis = "Row"; // unused
        string comparisonType = DropAxisShowAsToARowComparisonType.Text;
        string rowCaption = AxisShowAsToARowRowIndex.Text;
        string columnCaption = ""; //     AxisShowAsToARowColumnCaption;
        string pageIndex = AxisShowAsToARowPageIndex.SelectedValue;
        string rowIndex = AxisShowAsToARowRowIndex.Text;
        string columnIndex = "-1";
        string rowLag = "0";
        string columnLag = "0";

        string useRowCaption;
        if (rowIndex.Contains("#"))
            useRowCaption = "False";
        else
            useRowCaption = "True";

        string useColumnCaption = "False";

        string serverCommand = "Compare" + MyVariables.DelimForTokens
                                + "ToARow" + MyVariables.DelimForTokens
                                + comparisonType + MyVariables.DelimForTokens
                + agg + MyVariables.DelimForTokens
                + axis + MyVariables.DelimForTokens
                + rowCaption + MyVariables.DelimForTokens
                + columnCaption + MyVariables.DelimForTokens
                + rowIndex + MyVariables.DelimForTokens
                + columnIndex + MyVariables.DelimForTokens
                + rowLag + MyVariables.DelimForTokens
                + columnLag + MyVariables.DelimForTokens
                + useRowCaption + MyVariables.DelimForTokens
            + useColumnCaption + MyVariables.DelimForTokens
            + pageIndex + MyVariables.DelimForTokens;

        doCommonPostback(serverCommand, sender);
    }

    protected void btnShowAsSpecificColumn_Click(object sender, EventArgs e)
    {
        string agg = "Actual"; // unused
        string axis = "Column"; // unused
        string comparisonType = AxisShowAsPctToAColumnComparisonType.Text;
        string columnIndex = AxisShowAsPctToAColumnColumnIndex.Text;
        string rowCaption = ""; // 
        string columnCaption = AxisShowAsPctToAColumnColumnIndex.Text;
        string pageIndex = AxisShowAsPctToAColumnPageIndex.SelectedValue;
        string rowIndex = "-1";
        string rowLag = "0";
        string columnLag = "0";

        string useRowCaption = "False";

        string useColumnCaption;
        if (columnCaption.Contains("#"))
            useColumnCaption = "False";
        else
            useColumnCaption = "True";

        string serverCommand = "Compare" + MyVariables.DelimForTokens
                                + "ToAColumn" + MyVariables.DelimForTokens
                                + comparisonType + MyVariables.DelimForTokens
                    + agg + MyVariables.DelimForTokens
                    + axis + MyVariables.DelimForTokens
                    + rowCaption + MyVariables.DelimForTokens
                    + columnCaption + MyVariables.DelimForTokens
                    + rowIndex + MyVariables.DelimForTokens
                    + columnIndex + MyVariables.DelimForTokens
                    + rowLag + MyVariables.DelimForTokens
                    + columnLag + MyVariables.DelimForTokens
                    + useRowCaption + MyVariables.DelimForTokens
            + useColumnCaption + MyVariables.DelimForTokens
            + pageIndex + MyVariables.DelimForTokens;

        doCommonPostback(serverCommand, sender);
    }

    protected void DoPresetNtile(object sender, EventArgs e)
    {
        doNtile(PresetNtiles.SelectedValue, null);
        closeAllDlgs();
    }
    private void doNtile(string normalizeCount, object sender)
    {
        string normalizeAxis = NormalizeAxisFractile.Text;
        string cmd = "ChangeValuesToNtile" + MyVariables.DelimForTokens
            + "True" + MyVariables.DelimForTokens
            + normalizeAxis + MyVariables.DelimForTokens
            + normalizeCount;

        doCommonPostback(cmd, sender);
    }
    protected void NTile_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        string arg = btn.CommandArgument;
        if (arg != "" && arg.IndexOf("ClosePanels", StringComparison.CurrentCultureIgnoreCase) == -1)
        {
            NormalizeCount.Text = arg;  // there's a number in this arg....
        }

        doNtile(NormalizeCount.Text, sender);
    }

    protected void NormalizeRank_Click(object sender, EventArgs e)
    {
        string normalizeAxis = NormalizeAxisRank.Text;
        string cmd = "ChangeValuesToRank" + MyVariables.DelimForTokens
            + "False" + MyVariables.DelimForTokens +
            normalizeAxis;

        doCommonPostback(cmd, sender);
    }
    protected void Normalize8020_Click(object sender, EventArgs e)
    {
        string normalizeAxis = NormalizeAxis8020.Text;
        string percentArray = "2,0.2,0.8";
        string cmd = "ChangeValuesPercents" + MyVariables.DelimForTokens
            + "True" + MyVariables.DelimForTokens
            + normalizeAxis + MyVariables.DelimForTokens
            + percentArray;

        doCommonPostback(cmd, sender);

    }
    protected void AboveBelow_Click(object sender, EventArgs e)
    {
        string normalizeAggregation = AboveBelowAggregation.Text;
        string normalizeAxis = AboveBelowAxis.Text;
        string cmd = "ChangeValuesAboveBelowAggregation" + MyVariables.DelimForTokens
            + "True" + MyVariables.DelimForTokens
            + normalizeAxis + MyVariables.DelimForTokens
            + normalizeAggregation;

        this.doCommonPostback(cmd, sender);

    }

    protected void StdDev_Click(object sender, EventArgs e)
    {
        string axis = StdDevAxis.Text;
        string cmd = "ShowAsNumberStandardDeviations" + MyVariables.DelimForTokens + axis;

        this.doCommonPostback(cmd, sender);
    }
    protected void TestByComparison_Click(object sender, EventArgs e)
    {
        string selectedBaselineCaption = BaselineId.Text;
        if (selectedBaselineCaption.Length == 0)
            return;
        string comparisonOperator = BaselineComparisonOperator.Text;
        string percentBaselineValue = "0"; // only used for RangeWithin or RangeOutside document.getElementById( "BaselinePercentBaselineValue" ).value;
        string thresholdComparisonOperator = BaselineThresholdComparisonOperator.Text;
        string thresholdCount = BaselineThresholdCount.Text;
        string thresholdPercent = "0";
        string consecutive = BaselineConsecutive.Checked ? "True" : "False";
        string stopAtThresholdCount = BaselineStopAtThresholdCount.Checked ? "True" : "False";
        string asPercent = "False";
        string bWantFalseCount = "True";
        string FalseColumnCaption = BaselineFalseColumnCaption.Text;
        string bWantTrueCount = "True";
        string TrueColumnCaption = BaselineTrueColumnCaption.Text;
        string bWantOverallCount = "True";
        string FalseOverallCaption = BaselineOverallColumnCaption.Text;
        string wantCustomRange = "False";

        string cmd = "Test" + MyVariables.DelimForTokens
        + selectedBaselineCaption + MyVariables.DelimForTokens
        + comparisonOperator + MyVariables.DelimForTokens
        + percentBaselineValue + MyVariables.DelimForTokens
        + thresholdComparisonOperator + MyVariables.DelimForTokens
        + thresholdCount + MyVariables.DelimForTokens
        + thresholdPercent + MyVariables.DelimForTokens
        + consecutive + MyVariables.DelimForTokens
        + stopAtThresholdCount + MyVariables.DelimForTokens
        + asPercent + MyVariables.DelimForTokens
        + bWantFalseCount + MyVariables.DelimForTokens
        + FalseColumnCaption + MyVariables.DelimForTokens
        + bWantTrueCount + MyVariables.DelimForTokens
        + TrueColumnCaption + MyVariables.DelimForTokens
        + bWantOverallCount + MyVariables.DelimForTokens
        + FalseOverallCaption + MyVariables.DelimForTokens
        + wantCustomRange;

        this.doCommonPostback(cmd, sender);


    }
    protected void TestByComparisonR_Click(object sender, EventArgs e)
    {
        string selectedBaselineCaption = BaselineIdR.Text;
        if (selectedBaselineCaption.Length == 0)
            return;
        string comparisonOperator = BaselineComparisonOperatorR.Text;
        string percentBaselineValue = BaselinePercentBaselineValue.Text;
        string thresholdComparisonOperator = BaselineThresholdComparisonOperatorR.Text;
        string thresholdCount = BaselineThresholdCountR.Text;
        string thresholdPercent = "0";
        string consecutive = BaselineConsecutiveR.Checked ? "True" : "False";
        string stopAtThresholdCount = BaselineStopAtThresholdCountR.Checked ? "True" : "False";
        string asPercent = "True";
        string bWantFalseCount = "True";
        string FalseColumnCaption = BaselineFalseColumnCaptionR.Text;
        string bWantTrueCount = "True";
        string TrueColumnCaption = BaselineTrueColumnCaptionR.Text;
        string bWantOverallCount = "True";
        string FalseOverallCaption = BaselineOverallColumnCaptionR.Text;
        string wantCustomRange = "False";

        string cmd = "Test" + MyVariables.DelimForTokens
        + selectedBaselineCaption + MyVariables.DelimForTokens
        + comparisonOperator + MyVariables.DelimForTokens
        + percentBaselineValue + MyVariables.DelimForTokens
        + thresholdComparisonOperator + MyVariables.DelimForTokens
        + thresholdCount + MyVariables.DelimForTokens
        + thresholdPercent + MyVariables.DelimForTokens
        + consecutive + MyVariables.DelimForTokens
        + stopAtThresholdCount + MyVariables.DelimForTokens
        + asPercent + MyVariables.DelimForTokens
        + bWantFalseCount + MyVariables.DelimForTokens
        + FalseColumnCaption + MyVariables.DelimForTokens
        + bWantTrueCount + MyVariables.DelimForTokens
        + TrueColumnCaption + MyVariables.DelimForTokens
        + bWantOverallCount + MyVariables.DelimForTokens
        + FalseOverallCaption + MyVariables.DelimForTokens
        + wantCustomRange;

        this.doCommonPostback(cmd, sender);

    }

    protected void SwapAxes_Click(object sender, EventArgs e)
    {
        string cmd = "Swap";

        this.doCommonPostback(cmd, sender);

    }
    protected void SwapValuesWithRowLabels_Click(object sender, EventArgs e)
    {
        swapCellValueHelper("Row", sender);
    }
    protected void SwapValuesWithColumnLabels_Click(object sender, EventArgs e)
    {
        swapCellValueHelper("Column", sender);
    }
    private void swapCellValueHelper(string axis, object sender)
    {
        string cmd = "SwapCellValues" + MyVariables.DelimForTokens + axis;

        this.doCommonPostback(cmd, sender);

    }
    protected void Combine_Click(object sender, EventArgs e)
    {
        string axis = AxisCombine.Text;
        string agg = AggCombine.Text;
        string selectionMode = CombineSelectionMode.Text;
        string instructionsForselected = CombineInstructionsForSelected.Text;
        string instructionsForUnselected = CombineInstructionsForUnselected.Text;
        string caption = CombineCaption.Text;
        if (caption.Equals("", StringComparison.CurrentCultureIgnoreCase))
        {
            caption = selectionMode + " " + agg;
        }
        string onlyWantThisAsTrend = OnlyWantThisAsTrend.Checked ? "True" : "False";

        string cmd;
        if (OnlyWantThisAsTrend.Checked == false)
            cmd = "Combine";
        else
            cmd = "Makebaseline";

        cmd += MyVariables.DelimForTokens
        + axis + MyVariables.DelimForTokens
        + agg + MyVariables.DelimForTokens
        + selectionMode + MyVariables.DelimForTokens
        + instructionsForselected + MyVariables.DelimForTokens
        + instructionsForUnselected + MyVariables.DelimForTokens
        + caption + MyVariables.DelimForTokens
        + onlyWantThisAsTrend;

        this.doCommonPostback(cmd, sender);

    }

    protected void FilterByValue_Click(object sender, EventArgs e)
    {
        string cmd = FilterByValueCommand.Text;
        string op = FilterCompareOperator.Text;
        string axis = "Row";
        string colIndex = "-1";

        string compareVal = FilterValueToCompareTo.Text;
        string useCompareVal = "True";
        string percentThreshold = "0";
        string asPercent = "False";

        string caption = FilterValueColumns.SelectedValue;
        string agg = "Actual";
        string serverCommand = "FilterByValue" + MyVariables.DelimForTokens
            + cmd + MyVariables.DelimForTokens
            + op + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens
            + colIndex + MyVariables.DelimForTokens
            + caption + MyVariables.DelimForTokens
            + asPercent + MyVariables.DelimForTokens
            + percentThreshold + MyVariables.DelimForTokens
            + compareVal + MyVariables.DelimForTokens
            + useCompareVal + MyVariables.DelimForTokens + agg;

        this.doCommonPostback(serverCommand, sender);

    }

    protected void FilterByAxisValue_Click(object sender, EventArgs e)
    {
        string cmd = AxisFilterCommand.Text;
        string op = AxisFilterCompareOperator.Text;
        string axis = "Row";

        string compareVal = "0";
        string useCompareVal = "False";
        string percentThreshold;
        string asPercent;

        if (AxisFilterAsPercent.Checked)
        {
            asPercent = "True";
        }
        else
        {
            asPercent = "False";
        }
        percentThreshold = AxisFilterValueToCompareTo.Text;

        string colIndex = "-1";
        string caption = AxisFilterValueColumns.SelectedValue;
        string agg = AxisFilterAggregationToCompareTo.Text;
        string serverCommand = "FilterByValue" + MyVariables.DelimForTokens
            + cmd + MyVariables.DelimForTokens
            + op + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens
            + colIndex + MyVariables.DelimForTokens
            + caption + MyVariables.DelimForTokens
            + asPercent + MyVariables.DelimForTokens
            + percentThreshold + MyVariables.DelimForTokens
            + compareVal + MyVariables.DelimForTokens
            + useCompareVal + MyVariables.DelimForTokens
            + agg;

        this.doCommonPostback(serverCommand, sender);
    }

    protected void RemoveSelected_Click(object sender, EventArgs e)
    {
        string serverCommand = "RemoveSelected";

        this.doCommonPostback(serverCommand, sender);

    }

    protected void RemoveUnselected_Click(object sender, EventArgs e)
    {
        string serverCommand = "KeepSelected";

        this.doCommonPostback(serverCommand, sender);

    }

    protected void RollingCalc_Click(object sender, EventArgs e)
    {
        try
        {
            string periodCount = RollingPeriodCount.Text;
            string startAt = RollingStartingAt.Text;
            string stepBy = RollingStepBy.Text;
            string axis = "Column";
            string direction = RollingDirection.Text;
            int newStepBy;
            int intStepBy = Convert.ToInt32(stepBy);
            if (direction.Equals("Backward", StringComparison.CurrentCultureIgnoreCase))
                newStepBy = -1 * intStepBy;
            else
                newStepBy = intStepBy;
            string agg = AggregationRolling.Text;

            string serverCommand = "RollingPeriods" + MyVariables.DelimForTokens
                + axis + MyVariables.DelimForTokens
                + startAt + MyVariables.DelimForTokens
                + newStepBy + MyVariables.DelimForTokens
                + periodCount + MyVariables.DelimForTokens
                + agg;

            this.doCommonPostback(serverCommand, sender);
        }
        catch (System.FormatException) { }

    }

    protected void Cumulatives_Click(object sender, EventArgs e)
    {
        string axis = AxisCumulatives.Text;
        string agg = AggCumulatives.Text;
        string serverCommand = "MathOperation" + MyVariables.DelimForTokens
            + "Cumulative" + MyVariables.DelimForTokens
            + "0" + MyVariables.DelimForTokens
            + "0" + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens
            + "Cumul" + agg;

        this.doCommonPostback(serverCommand, sender);

    }
    protected void Distribute_Click(object sender, EventArgs e)
    {
        string op = DistributionFormula.Text;
        string pageIndexToCompareTo = DistributionPageToImitateIndex.SelectedValue;
        string param2 = "0"; // unused in this release
        string serverCommand = "distributecellcollection" + MyVariables.DelimForTokens
            + op + MyVariables.DelimForTokens
            + pageIndexToCompareTo + MyVariables.DelimForTokens
            + param2;

        this.doCommonPostback(serverCommand, sender);


    }
    protected void MathOperation_Click(object sender, EventArgs e)
    {
        string op = MathOperationAgg.Text;
        string axis = "row"; // unused in this type of mathoperation i.e. non-cumulate operations
        string agg = "Actual";  // unused in this type of mathoperation i.e. non-cumulate operations
        string param1 = MathOperationParam1.Text;
        string param2 = "0"; // unused in this release

        string serverCommand = "MathOperation" + MyVariables.DelimForTokens
            + op + MyVariables.DelimForTokens
            + param1 + MyVariables.DelimForTokens
            + param2 + MyVariables.DelimForTokens
            + axis + MyVariables.DelimForTokens + agg;
        this.doCommonPostback(serverCommand, sender);

    }


    protected void FilterByCaptionFromAnotherPage_Click(object sender, EventArgs e)
    {
        string action = FilterByCaptionFromAnotherPageAction.Text;
        string axis = "Row";
        string propertyIndex = "-1";
        string fromPage = "True";
        string pageIndex = FilterByCaptionFromAnotherPagePageIndex.SelectedValue;
        string fromFile = "False";
        string fileName = "";
        string fromUserText = "False";
        string operatorType = "ExactMatch";
        string captionCount = "0";
        string caption = "";

        string serverCommand = "selectbycaptions"
            + MyVariables.DelimForTokens + action
            + MyVariables.DelimForTokens + axis
            + MyVariables.DelimForTokens + propertyIndex
            + MyVariables.DelimForTokens + fromPage
            + MyVariables.DelimForTokens + pageIndex
            + MyVariables.DelimForTokens + fromFile
            + MyVariables.DelimForTokens + fileName
            + MyVariables.DelimForTokens + fromUserText
            + MyVariables.DelimForTokens + operatorType
            + MyVariables.DelimForTokens + captionCount
            + MyVariables.DelimForTokens + caption;
        this.doCommonPostback(serverCommand, sender);

    }
    protected void FilterByPropertyValue_Click(object sender, EventArgs e)
    {
        string action = FilterByCaptionFromAPropertyValueAction.SelectedValue;
        string axis = "Row";
        string propertyIndex = FilterByCaptionFromAPropertyIndex.SelectedValue;
        string fromPage = "False";
        string pageIndex = "-1";
        string fromFile = "False";
        string fileName = "";
        string fromUserText = "True";
        string operatorType = FilterByPropertyValueMatchType.SelectedValue;
        string captionCount = "1";
        string caption = FilterByCaptionFromAPropertyValue.Text;

        string serverCommand = "selectbycaptions"
            + MyVariables.DelimForTokens + action
            + MyVariables.DelimForTokens + axis
            + MyVariables.DelimForTokens + propertyIndex
            + MyVariables.DelimForTokens + fromPage
            + MyVariables.DelimForTokens + pageIndex
            + MyVariables.DelimForTokens + fromFile
            + MyVariables.DelimForTokens + fileName
            + MyVariables.DelimForTokens + fromUserText
            + MyVariables.DelimForTokens + operatorType
            + MyVariables.DelimForTokens + captionCount
            + MyVariables.DelimForTokens + caption;
        this.doCommonPostback(serverCommand, sender);

    }
    protected void FilterByCaptionValue_Click(object sender, EventArgs e)
    {
        string action = FilterByCaptionFromThisPageAction.SelectedValue;
        string axis = "Row";
        string propertyIndex = "-1";
        string fromPage = "False";
        string pageIndex = "-1";
        string fromFile = "False";
        string fileName = "";
        string fromUserText = "True";
        string operatorType = FilterByCaptionMatchType.SelectedValue;
        string captionCount = "1";
        string caption = FilterByCaptionFromThisPageCaption.Text;

        string serverCommand = "selectbycaptions"
            + MyVariables.DelimForTokens + action
            + MyVariables.DelimForTokens + axis
            + MyVariables.DelimForTokens + propertyIndex
            + MyVariables.DelimForTokens + fromPage
            + MyVariables.DelimForTokens + pageIndex
            + MyVariables.DelimForTokens + fromFile
            + MyVariables.DelimForTokens + fileName
            + MyVariables.DelimForTokens + fromUserText
            + MyVariables.DelimForTokens + operatorType
            + MyVariables.DelimForTokens + captionCount
            + MyVariables.DelimForTokens + caption;
        this.doCommonPostback(serverCommand, sender);
    }

    private string getSelectedColumnIndexesAsCSV(object sender, Data.Page thePage)
    {
        bool bPageDefault = false;

        Control control = (Control)sender;
        string type = sender.GetType().ToString();
        if (type.IndexOf("button", StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            Button btn = (Button)sender;
            string arg = btn.CommandArgument;
            if (arg.IndexOf("PageDefault", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                bPageDefault = true;
            }
        }

        if (bPageDefault)
        {
            return "-1";  // count of 1 and the index of -1 that indicates to do the page default
        }
        else if (thePage.AnySelected( "column" ) )
        {
            return "selectedcolumns";
        }
        else
            return "-1";
    }

    protected void DoModifyAlertNone(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            if (currentPage == null) return;

            string wantDefault = "";
            Control control = (Control)sender;
            string type = sender.GetType().ToString();
            if (type.IndexOf("button", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                Button btn = (Button)sender;
                string arg = btn.CommandArgument;
                if (arg.IndexOf("ApplyDefault", StringComparison.CurrentCultureIgnoreCase) > -1)
                {
                    wantDefault = "ApplyDefault";
                }
            }

            string alertResponse = "ChangeAlertTo" + MyVariables.DelimForTokens;

            alertResponse += "none" + MyVariables.DelimForTokens;
            alertResponse += wantDefault + MyVariables.DelimForTokens;
            alertResponse += this.getSelectedColumnIndexesAsCSV(sender, currentPage);

            string serverCommand = alertResponse;
            doCommonPostback(serverCommand, sender);
        }
    }
    protected void DoModifyAlertToAnotherCell(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            if (currentPage == null) return;

            string alertResponse = "ChangeAlertTo" + MyVariables.DelimForTokens;

            alertResponse += "relativecell" + MyVariables.DelimForTokens;
            string pageIndex;
            int index = AlertCompareToAnotherCellPages.SelectedIndex;
            if (index != -1)
                pageIndex = AlertCompareToAnotherCellPages.SelectedValue;
            else
                pageIndex = "-1";
            alertResponse += pageIndex + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeRow.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeRowFixed.Checked.ToString() + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeColumn.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeColumnFixed.Checked.ToString() + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeThreshold.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAnotherCellRelativeThresholdAsPercent.Checked.ToString() + MyVariables.DelimForTokens;
            alertResponse += AlertToAnotherCellCSS.SelectedValue + MyVariables.DelimForTokens;
            alertResponse += this.getSelectedColumnIndexesAsCSV(sender, currentPage);

            string serverCommand = alertResponse;
            doCommonPostback(alertResponse, sender);
        }
    }
    protected void DoModifyAlertToAxis(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            if (currentPage == null) return;

            string alertResponse = "ChangeAlertTo" + MyVariables.DelimForTokens;

            alertResponse += "axis" + MyVariables.DelimForTokens;

            string pageIndex;
            int index = AlertCompareToAxisPages.SelectedIndex;
            if (index != -1)
                pageIndex = AlertCompareToAxisPages.SelectedValue;
            else
                pageIndex = "-1";
            alertResponse += pageIndex + MyVariables.DelimForTokens;

            alertResponse += AlertCompareToAxisAxes.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAxisAggregations.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAxisThreshold.Text + MyVariables.DelimForTokens;
            alertResponse += AlertCompareToAxisThresholdAsPercent.Checked.ToString() + MyVariables.DelimForTokens;
            alertResponse += AlertToAxisCSS.SelectedValue + MyVariables.DelimForTokens;
            alertResponse += this.getSelectedColumnIndexesAsCSV(sender, currentPage);

            string serverCommand = alertResponse;
            doCommonPostback(serverCommand, sender);
        }
    }
    protected void DoModifyAlertUsingCellValues(object sender, EventArgs e)
    {
        if (currentData != null)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            if (currentPage == null) return;

            string alertResponse = "ChangeAlertTo" + MyVariables.DelimForTokens;

            alertResponse += "cellvalue" + MyVariables.DelimForTokens;

            string pageIndex;
            int index = AlertUsingCellValuesPages.SelectedIndex;
            if (index != -1)
                pageIndex = AlertUsingCellValuesPages.SelectedValue;
            else
                pageIndex = "-1";

            alertResponse += pageIndex + MyVariables.DelimForTokens;
            alertResponse += CSSprefixesGroups.SelectedValue + MyVariables.DelimForTokens;
            alertResponse += this.getSelectedColumnIndexesAsCSV(sender, currentPage);

            string serverCommand = alertResponse;
            doCommonPostback(serverCommand, sender);
        }
    }

    private void toggleDlg(Panel desiredDlg)
    {
        if (desiredDlg == null)
            return;

        desiredDlg.Visible = true;
    }

    private void togglePanel(Panel visiblePanel, Button visibleButton, Button[] deselectedButtons, Panel[] deselectedPanel)
    {
        closeAllDlgs();

        Panel parent = (Panel)visiblePanel.Parent;
        visiblePanel.Visible = parent.Visible = !visiblePanel.Visible;
        visibleButton.Attributes["class"] = "SelectedBtn";

        foreach (Button desel in deselectedButtons)
        {
            desel.Attributes["class"] = "UnSelectedBtn";
        }
        foreach (Panel desel in deselectedPanel)
        {
            desel.Attributes["class"] = "";
            desel.Visible = false;
        }
    }

    private bool testCloseAll(object sender)
    {
        if (sender == null) return false;

        try
        {
            Control control = (Control)sender;
            string type = sender.GetType().ToString();
            if (type.IndexOf(".button", StringComparison.CurrentCultureIgnoreCase) > -1)   // beware of false positive on "imagebutton"
            {
                Button btn = (Button)sender;
                string arg = btn.CommandArgument;
                if (arg.IndexOf("ClosePanels", StringComparison.CurrentCultureIgnoreCase) > -1)
                {
                    return true;
                }
            }
        }
        catch (InvalidCastException) { }; // 

        return false;

    }

    private void runScript(string fileName)
    {
        string serverCommand = "RunScript" + MyVariables.DelimForTokens + fileName;
        doCommonPostback(serverCommand, true);
    }

    private bool doCommonPostback(string commandScript, object sender)
    {
        bool closeUI = testCloseAll(sender);
        if (closeUI)
            closeAllDlgs();

        if (currentData != null)
        {
            Data.Page currentPage = currentData.GetSelectedPage();
            int originalPageCount = currentData.GetPageCount();

            bool result = false;
            if (commandScript.Length > 0 && commandScript.StartsWith(";") == false)
            {
                if (currentPage != null)
                {
                    int selRowIndex = currentPage.GetFirstSelected( "row" );
                    if (selRowIndex != -1)
                    {
                        string rowCaption = currentPage.GetRowLabelValue( selRowIndex );
                        FindText.Text = rowCaption;
                    }
                }

                result = runScript(commandScript, currentData, IsPostBack == false);

                currentPage = currentData.GetSelectedPage();
                if (currentPage != null)
                {
                    LoadControlsThatNeedFreshData(currentPage);
                }
            }

            makeChart(false);
            // Response.Flush();        // commented out because the performance gain is slight (if any) but it hampers any follow on redirect

            if (result)
            {
                if (currentPage != null )
                {
                    if (cmdIsEligibleForSave(commandScript))
                    {
                        appendItemToInteractiveUpdates(commandScript);
                    }
                }
                populateProjectScriptBox();
                return true;
            }
            else
            {
                Response.Write("Error occurred or Session Timed Out"); // todo: localize
            }
        }

        return false;
    }

    private bool cmdIsEligibleForSave(string command)
    {
        string[] commandsDontLogToInteractive = {
            "saveasproject",
            "saveprojectfilewithnewtransactions"
        };

        foreach (string keyword in commandsDontLogToInteractive)
            if (command.StartsWith(keyword + MyVariables.DelimForTokens, StringComparison.CurrentCultureIgnoreCase))
                return false;

        return true;
    }

    private void appendItemToInteractiveUpdates(string command)
    {
        if (ViewState["InteractiveUpdates"] == null)
            ViewState["InteractiveUpdates"] = new List<String>();

        List<String> temp = (List<String>)ViewState["InteractiveUpdates"];
        if( temp != null )
            temp.Add( command );
    }

    private void appendItemToInteractiveUpdates(ArrayList commands)
    {
        foreach (string command in commands)
            appendItemToInteractiveUpdates(command);
    }

    protected void DoAutopopulate(object sender, EventArgs e)
    {
        if (currentData == null)
            return;

        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string serverCommand = "autopopulatebaselines";
            doCommonPostback(serverCommand, sender);
        }

    }



    private HtmlTableCell appendGeneralTD(string cellId, string cssClass, string selectionState,
    string innerText)
    {
        return resultableTDForSelection(cellId, cssClass, selectionState, innerText);
    }

    private HtmlTableCell appendColumnCaptionTD(string cellId, string cssClass, string selectionState,
        string innerText, Data.Page selPage, int columnIndex)
    {
        string actionPrequal = cellId;
        return resultableTDForSelection(actionPrequal, cssClass, selectionState, innerText);
    }

    private HtmlTableCell appendRowLabelTD(string cellId, string cssClass, string selectionState,
        string innerText, Data.Page selPage, int rowIndex)
    {
        string actionPrequal = cellId;
        return resultableTDForSelection(actionPrequal, cssClass, selectionState, innerText);
    }

    private HtmlTableCell appendCellTD(string cellId, string cssClass, string selectionState,
        string innerText, Data.Page selPage, int rowIndex, int columnIndex)
    {
        string actionPrequal = cellId;
        return resultableTDForSelection(actionPrequal, cssClass, selectionState, innerText);
    }

    protected void HtmlAnchor_Click(object sender, EventArgs e)
    {
        HtmlAnchor eventedAnchor = (HtmlAnchor)sender;
        if (eventedAnchor.InnerText.IndexOf("http", StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            string urlFromCell = ""; //  dc.getPromptCollection().DoReplaceKeys(eventedAnchor.InnerText);
            Response.Redirect(urlFromCell, true);
        }
        else
        {
            string clickedOnUID = eventedAnchor.ID;
            string cmd = eventedAnchor.Attributes["myCommand"];
            if (cmd != null)
            {
                if (cmd.StartsWith("script,", StringComparison.CurrentCultureIgnoreCase))  // or sorttextcolumn or sortrowlabel
                {
                    int index = cmd.IndexOf(MyVariables.DelimForTokens);
                    string actualCommand = cmd.Substring(index + 1);

                    doCommonPostback(actualCommand, sender);
                }
            }
            else
                doCommonPostback(clickedOnUID, sender);
        }
    }

    private HtmlTableCell resultableTDForScript(string uniqueCellId, string command, string cssClass,
        string selectionState, string innerText)
    {
        HtmlTableCell td = new HtmlTableCell();
        td.Attributes["class"] = cssClass;


        HtmlAnchor thisAnchor = new HtmlAnchor();
        thisAnchor.EnableViewState = true;
        thisAnchor.ServerClick += HtmlAnchor_Click;
        thisAnchor.ID = uniqueCellId;
        thisAnchor.InnerText = innerText;
        thisAnchor.Attributes["class"] = cssClass + " myanchor";
        thisAnchor.Attributes["myCommand"] = "script" + MyVariables.DelimForTokens + command;

        td.Controls.Add(thisAnchor);

        return td;
    }


    private HtmlTableCell resultableTDForSelection(string cellId, string cssClass,
        string selectionState, string innerText)
    {
        HtmlTableCell td = new HtmlTableCell();
        td.Attributes["class"] = cssClass;


        if (innerText.IndexOf("http:", StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            HtmlAnchor remoteAnchor = new HtmlAnchor();
            remoteAnchor.InnerText = innerText;
            remoteAnchor.ID = cellId;
            remoteAnchor.ServerClick += HtmlAnchor_Click;
            td.Controls.Add(remoteAnchor);
        }
        else
        {

            if (selectionState.Equals("f", StringComparison.CurrentCultureIgnoreCase)
                || selectionState.Equals("t", StringComparison.CurrentCultureIgnoreCase)
                )
            {
                HtmlAnchor thisAnchor = new HtmlAnchor();
                thisAnchor.EnableViewState = true;
                thisAnchor.ServerClick += HtmlAnchor_Click;

                string commmand = "";

                if (selectionState.Equals("t", StringComparison.CurrentCultureIgnoreCase))
                {
                    thisAnchor.InnerHtml = innerText;
                    commmand = "unselect";
                }
                else
                {
                    thisAnchor.InnerHtml = innerText;
                    commmand = "select";
                }

                commmand += MyVariables.DelimForTokens + cellId;

                thisAnchor.ID = commmand;
                thisAnchor.Attributes["myCommand"] = "script" + MyVariables.DelimForTokens + commmand;
                thisAnchor.Attributes["class"] = cssClass + " myanchor";

                td.Controls.Add(thisAnchor);
            }
            else
            {
                Label label = new Label();
                label.Text = innerText;
                label.ID = "nonsel" + MyVariables.DelimForTokens + cellId;
                //label.Attributes["class"] = cssClass;
                td.Controls.Add(label);
            }
        }
        return td;
    }


    protected void DoSort(object sender, EventArgs e)
    {
        int selIndex = SortColumns.SelectedIndex;
        if (selIndex == -1)
            return;

        string value = SortColumns.SelectedItem.Value;
        string ascendingFlag = SortOrder.SelectedValue;

        string serverCommand;
        if (value.StartsWith("SortTextColumn", StringComparison.CurrentCultureIgnoreCase))
        {
            string[] tokens = value.Split(',');
            serverCommand = "sorttextcolumn" + MyVariables.DelimForTokens + tokens[1] + MyVariables.DelimForTokens + ascendingFlag;
        }
        else if (value.StartsWith("SortRowLabel", StringComparison.CurrentCultureIgnoreCase))
        {
            serverCommand = "sortrowlabel" + MyVariables.DelimForTokens + ascendingFlag;
        }
        else
        {
            string caption = (string)SortColumns.SelectedItem.Text;
            serverCommand = "sort" + MyVariables.DelimForTokens + caption + MyVariables.DelimForTokens + ascendingFlag;
        }
        this.doCommonPostback(serverCommand, sender);
    }

    public void DoSortAscending_Click(object sender, EventArgs e)
    {
        doSortSelectedDataColumn(false, sender);
    }
    public void DoSortDescending_Click(object sender, EventArgs e)
    {
        doSortSelectedDataColumn(true, sender);
    }

    private void doSortSelectedDataColumn(bool descendingFlag, object sender)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        int selIndex = currentPage.GetFirstSelected( "column" );
        if (selIndex != -1)
        {
            string caption = currentPage.GetNumericColumnName(selIndex);
            string serverCommand = "sort" + MyVariables.DelimForTokens + caption + MyVariables.DelimForTokens + descendingFlag.ToString();
            this.doCommonPostback(serverCommand, sender);
        }
    }


    private void doFilterBySelectedColumn(object sender, string op)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        int selIndex = currentPage.GetFirstSelected( "column" );
        double val = currentPage.GetSelectedCellValue();
        if (val != Data.Data.BadNum() && selIndex != -1)
        {
            string cmd = "KeepByVal";
            string axis = "Row";

            string colIndex = "-1";
            string caption = currentPage.GetNumericColumnName( selIndex ) ;

            string compareVal = val.ToString();
            string useCompareVal = "True";
            string percentThreshold = "0";
            string asPercent = "False";

            string agg = "Actual";

            string serverCommand = "FilterByValue" + MyVariables.DelimForTokens
                + cmd + MyVariables.DelimForTokens
                + op + MyVariables.DelimForTokens
                + axis + MyVariables.DelimForTokens
                + colIndex + MyVariables.DelimForTokens
                + caption + MyVariables.DelimForTokens
                + asPercent + MyVariables.DelimForTokens
                + percentThreshold + MyVariables.DelimForTokens
                + compareVal + MyVariables.DelimForTokens
                + useCompareVal + MyVariables.DelimForTokens
                + agg;

            this.doCommonPostback(serverCommand, sender);
        }
    }

    protected void doReverseAxis(object sender, EventArgs e)
    {
        string cmd = "Reverse" + MyVariables.DelimForTokens;
        cmd += ReverseAxis.Text;
        string serverCommand = cmd;
        this.doCommonPostback(serverCommand, sender);
    }
    protected void doMoveRows(object sender, EventArgs e)
    {
        try
        {
            string cmd = "MoveRows" + MyVariables.DelimForTokens;
            cmd += MoveRowsAction.Text + MyVariables.DelimForTokens;

            string pageString;
            int selIndex = Convert.ToInt16(MoveRowsPages.SelectedValue);
            if (selIndex == -1)
            {// provide a value even if they didn't select something (highly unlikely since there is a default selected item)
                pageString = "-1";
            }
            else
            {
                int pageIndex = Convert.ToInt16(MoveRowsPages.Items[selIndex].Value);
                pageString = currentData.GetPage(pageIndex).GetPageCaption();
            }

            cmd += pageString + MyVariables.DelimForTokens;

            cmd += MoveRowsPosition.Text + MyVariables.DelimForTokens;
            cmd += MoveRowsDestinationInstructions.Text;

            string serverCommand = cmd;
            this.doCommonPostback(serverCommand, sender);
        }
        catch (System.FormatException) { }
    }
    protected void doMoveColumns(object sender, EventArgs e)
    {
        try
        {
            string cmd = "MoveColumns" + MyVariables.DelimForTokens;
            cmd += MoveColumnsAction.Text + MyVariables.DelimForTokens;

            int selIndex = Convert.ToInt16(MoveColumnsPages.SelectedValue);

            string pageString;
            if (selIndex == -1)
            {// provide a value even if they didn't select something (highly unlikely since there is a default selected item)
                pageString = "-1";
            }
            else
            {
                int pageIndex = Convert.ToInt16(MoveColumnsPages.Items[selIndex].Value );
                pageString = currentData.GetPage(pageIndex).GetPageCaption();
            }
            cmd += pageString + MyVariables.DelimForTokens;
            cmd += MoveColumnsPosition.Text + MyVariables.DelimForTokens;
            cmd += MoveColumnsDestinationInstructions.Text;
            string serverCommand = cmd;
            this.doCommonPostback(serverCommand, sender);
        }
        catch (System.FormatException) { }
    }
    protected void doMoveColumnToPages(object sender, EventArgs e)
    {
        string cmd = "movecolumnvaluestopages" + MyVariables.DelimForTokens;

        cmd += MoveColumnToPagesPagePrefix.Text + MyVariables.DelimForTokens;
        cmd += MoveColumnToPagesColumns.SelectedValue;
        string serverCommand = cmd;
        this.doCommonPostback(serverCommand, sender);
    }

    protected void doChangeLabelCaption(object sender, EventArgs e)
    {
        // invoke the function which finds the oldcaption and gives it a new name
        string cmd = "changelabelcaption" + MyVariables.DelimForTokens;
        cmd += RenameLabelsAllPages.Checked.ToString() + MyVariables.DelimForTokens;
        cmd += RenameLabelsAxis.SelectedValue + MyVariables.DelimForTokens;
        cmd += RenameLabelsOldColumnCaption.Text + MyVariables.DelimForTokens;
        cmd += RenameLabelsNewColumnCaption.Text;
        string serverCommand = cmd;
        this.doCommonPostback(serverCommand, sender);
    }

    protected void doAddAutoAggregate(object sender, EventArgs e)
    {
        if (currentData == null)
            return;

        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string serverCommand = "addaggregates" + MyVariables.DelimForTokens + AutoAggregateAxis.SelectedValue;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doNormalizeCustomRange(object sender, EventArgs e)
    {
        if (currentData == null)
            return;

        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string cmd;

            if (NormalizeCustomRangeAsPercent.Checked)
                cmd = "changevaluespercents" + MyVariables.DelimForTokens;
            else
                cmd = "changevaluesvalues" + MyVariables.DelimForTokens;
            cmd += NormalizeCustomRangeDescendingFlag.Checked.ToString() + MyVariables.DelimForTokens;
            cmd += NormalizeCustomRangeAxis.SelectedValue + MyVariables.DelimForTokens;
            string proposedNumbers = NormalizeCustomRangeValues.Text;
            string[] tokens = proposedNumbers.Split(',');
            if (tokens.Length > 0)
            {
                // todo: if it is percent, we *might* want to divide each value by 100 i.e. 25% is supposed to be .25 in the DC.
                cmd += tokens.Length.ToString() + MyVariables.DelimForTokens;
                foreach (string number in tokens)
                {
                    cmd += number + MyVariables.DelimForTokens;
                }

                string serverCommand = cmd;
                doCommonPostback(serverCommand, sender);
            }
        }
    }

    protected void doAddSelectedRowAsTrend(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string cmd = "addbaseline" + MyVariables.DelimForTokens;
            int rowIndex = currentPage.GetFirstSelected( "row" );
            if (rowIndex != -1)
            {
                string serverCommand = cmd + rowIndex.ToString();
                doCommonPostback(serverCommand, sender);
            }
        }
    }

    protected void doAssignColumnCSS(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            // allPages, allColumns | columnCaption, formatString;
            string cmd = "assigncolumncss" + MyVariables.DelimForTokens;
            cmd += getSelectedItemsFromListBox(this.AssignColumnFormatColumns);
            cmd += AssignColumnCSS.Text + MyVariables.DelimForTokens;
            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    private string getSelectedItemsFromListBox(System.Web.UI.WebControls.ListBox listBox)
    {
        string csv = "";
        int selCount = 0;
        for (int listIndex = 0, listCount = listBox.Items.Count; listIndex < listCount; listIndex++)
        {
            ListItem li = listBox.Items[listIndex];
            if (li.Selected || listBox.SelectedIndex == -1)    // if nothing is selected, then assume they meant to ask for them all
            {
                selCount++;
                string caption = li.Text;   // text is the caption, value is the index
                csv += caption + MyVariables.DelimForTokens;
            }
        }
        return selCount.ToString() + MyVariables.DelimForTokens + csv;     // n.b. csv has a trailing comma
    }

    private string getAllColumnCaptionsAsList(Data.Page currentPage)
    {
        string retVal = "";
        int colCount = currentPage.GetNumericColumnCount();
        int selCount = 0;

        for (int colIndex = 0; colIndex < colCount; colIndex++)
        {
            if (currentPage.GetSelectedPosition( "column", colIndex) || currentPage.AnySelected( "column" ) == false)
            {
                selCount++;

                if (retVal != "")
                    retVal += MyVariables.DelimForTokens;

                retVal += currentPage.GetNumericColumnName(colIndex);
            }
        }
        retVal = selCount + MyVariables.DelimForTokens + retVal + MyVariables.DelimForTokens;
        return retVal;
    }

    protected void doAssignWordsToValues(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string subcmd = "" + "~";    // we want one blank one for format zero...
            subcmd += AssignColumnFormat0.Text + "~";
            subcmd += AssignColumnFormat1.Text + "~";
            subcmd += AssignColumnFormat2.Text + "~";
            subcmd += AssignColumnFormat3.Text + "~";
            subcmd += AssignColumnFormat4.Text + "~";
            subcmd += AssignColumnFormat5.Text + "~";
            subcmd += AssignColumnFormat6.Text + "~";
            subcmd += AssignColumnFormat7.Text + "~";
            subcmd += AssignColumnFormat8.Text + "~";
            subcmd += AssignColumnFormat9.Text + "~";

            // allPages, allColumns | columnCaption, formatString;
            string cmd = "assignwordstovalues" + MyVariables.DelimForTokens;
            cmd += "false" + MyVariables.DelimForTokens;
            cmd += subcmd + MyVariables.DelimForTokens;

            cmd += getAllColumnCaptionsAsList(currentPage);
            // cmd += MyVariables.DelimForTokens;

            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doAssignCellFormat(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            if (PanelCellFormatInvert.Checked)
            {
                for (int listIndex = 0, listCount = PanelCellFormatListbox.Items.Count; listIndex < listCount; listIndex++)
                {
                    ListItem li = (ListItem)PanelCellFormatListbox.Items[listIndex];
                    li.Selected = !li.Selected;
                }
            }

            string cmd = "assigncellformat" + MyVariables.DelimForTokens;
            cmd += PanelCellFormatAllPages.Checked.ToString() + MyVariables.DelimForTokens;
            cmd += PanelCellFormatNumericFormat.Text + MyVariables.DelimForTokens; // todo: wrap this in delimiters so that they can enter comma if they want to
            cmd += getSelectedItemsFromListBox(this.PanelCellFormatListbox);

            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doDeleteTextColumn(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string serverCommand = "deletetextcolumn" + MyVariables.DelimForTokens;
            serverCommand += SwapTextColumnWithColumnPropertyIndex3.Text;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doMoveUniqueTextColumnToPages(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string serverCommand = "movetextcolumnvaluestopages" + MyVariables.DelimForTokens;
            serverCommand += SwapTextColumnWithColumnPropertyIndex2.Text;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doSwapTextColumnWithColumn(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            // allPages, allColumns | columnCaption, formatString;
            string serverCommand = "swaptextcolumnwithcolumnbyindex" + MyVariables.DelimForTokens;
            serverCommand += SwapTextColumnWithColumnPropertyIndex.Text;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doSwapTextColumnWithRowLabel(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            // allPages, allColumns | columnCaption, formatString;
            string cmd = "swaptextcolumnwithrowlabelbyindex" + MyVariables.DelimForTokens;
            cmd += this.SwapTextColumnRowLabelPropertyIndex.Text;
            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }


    protected void SelectRange(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string cmd = "selectrange" + MyVariables.DelimForTokens;
            cmd += SelectRangeAxis.SelectedValue + MyVariables.DelimForTokens;
            cmd += SelectRangeStart.Text + MyVariables.DelimForTokens;
            cmd += SelectRangeCount.Text;
            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void DoClearAllSelection(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null)
            return;

        string cmd = "ClearSelection" + MyVariables.DelimForTokens + "true" + MyVariables.DelimForTokens + "true";
        doCommonPostback(cmd, sender);

    }

    protected void doInvertRows(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string cmd = "invertselection" + MyVariables.DelimForTokens + "true" + MyVariables.DelimForTokens + "false";
            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void doInvertColumns(object sender, EventArgs e)
    {
        if (currentData == null)
            return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage != null)
        {
            string cmd = "invertselection" + MyVariables.DelimForTokens + "false" + MyVariables.DelimForTokens + "true";
            string serverCommand = cmd;
            doCommonPostback(serverCommand, sender);
        }
    }

    protected void SwitchToChooseProject(object sender, EventArgs e)
    {
        lh.SetProjectCaption(FilenameToSaveTo.Text);
        Response.Redirect("OpenChooseProject.aspx", true);
    }

    protected void SwitchToQuickView(object sender, EventArgs e)
    {
        lh.SetProjectCaption(FilenameToSaveTo.Text);
        Response.Redirect("OpenQuickView.aspx", true);
    }

    void SwitchToViewProject()
    {
        lh.SetProjectCaption(FilenameToSaveTo.Text);
        Response.Redirect("OpenAuthorMode.aspx", true);
    }

    protected void doShowRenamePageCaption(object sender, EventArgs e)
    {
        PageCaptionEditPanel.Visible = !PageCaptionEditPanel.Visible;

        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        PageCaptionNew.Text = currentPage.GetPageCaption();
        PageDescriptionNew.Text = currentPage.GetPageDescription();
    }

    protected void DoChangeCaption(object sender, EventArgs e)
    {
        PageCaptionEditPanel.Visible = false;

        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        if (PageCaptionNew.Text.IndexOf(MyVariables.DelimForTokens, StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            PageCaptionNew.Text = "\"" + PageCaptionNew.Text + "\"";
        }
        if (PageDescriptionNew.Text.IndexOf(MyVariables.DelimForTokens, StringComparison.CurrentCultureIgnoreCase) > -1)
        {
            PageDescriptionNew.Text = "\"" + PageDescriptionNew.Text + "\"";
        }

        int index = currentPage.GetIndex();
        string serverCommand = "PageCaption" + MyVariables.DelimForTokens
                + PageCaptionNew.Text + "~"
                + PageDescriptionNew.Text
                ;
        doCommonPostback(serverCommand, sender);
    }

    protected void DoChangeSelectedPage(object sender, EventArgs e)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        try
        {
            int index = Convert.ToInt16(ChangeSelectedPage.SelectedValue);
            if (index != -1)
            {
                string serverCommand = "Select" + MyVariables.DelimForTokens + "Page" + MyVariables.DelimForTokens + index;
                doCommonPostback(serverCommand, sender);
            }
        }
        catch (System.FormatException) { }

    }

    private bool canSave()
    {
        if (currentData == null)
            return false;
        bool userCanSave = lh.GetUserCanSave();
        if (userCanSave == false)
            return false;

        return true;

    }

    protected void DoAdminSaveAsProject(object sender, EventArgs e)
    {
        if (canSave() == false) return;

        string cmd = "SaveAsProject" + MyVariables.DelimForTokens 
            + AdminSaveAsProjectFileName.Text + MyVariables.DelimForTokens 
            + this.interactiveUpdateTemporaryComment;

        if (doCommonPostback(cmd, sender))
        {
            ViewState["InteractiveUpdates"] = null;

            lh.SetProjectCaption(AdminSaveAsProjectFileName.Text);

            string viewer = lh.GetViewer();
            string newURL = lh.RedirectInfo(viewer, AdminSaveAsProjectFileName.Text);
            Response.Redirect(newURL, true); // if it performs a Response.Flush we can no longer Redirect.
        }

    }

    protected void DoAdminSaveAsProjectForNod(object sender, EventArgs e)
    {
        if (canSave() == false) return;

        string cmd = "SaveAsProjectForNod" + MyVariables.DelimForTokens + AdminSaveAsProjectFileNameForNod.Text + MyVariables.DelimForTokens + this.interactiveUpdateTemporaryComment;
        if (doCommonPostback(cmd, sender))
        {
            ViewState["InteractiveUpdates"] = null;

            lh.SetProjectCaption(AdminSaveAsProjectFileNameForNod.Text);

            string viewer = lh.GetViewer();
            string newURL = lh.RedirectInfo(viewer, AdminSaveAsProjectFileNameForNod.Text);
            Response.Redirect(newURL, true); // if it performs a Response.Flush we can no longer Redirect.
        }

    }


    protected void DoAdminSaveProjectScript(object sender, EventArgs e)
    {
        if (canSave() == false) return;
        // save the interactive updates into a file that has the same name as the project filenames
        // update the dataclass object to show that it has this script that needs to be executed after opening
        // save the dataclass object (dataclass aka proejct)

        string cmd = "SaveProjectFileWithNewTransactions" + MyVariables.DelimForTokens + this.interactiveUpdateTemporaryComment;
        if (doCommonPostback(cmd, sender))
        {
            ViewState["InteractiveUpdates"] = null;
        }
    }

    protected void DoAdminSavePageExported(object sender, EventArgs e)
    {
        string fileName = AdminSavePageExportedFileName.Text;
        string cmd = "";
        cmd = ExportFormats.SelectedValue + MyVariables.DelimForTokens + fileName + MyVariables.DelimForTokens + "True";
        doCommonPostback(cmd, sender);
    }

    protected void DoAdminAddData(object sender, EventArgs e)
    {
        if (canSave() == false) return;

        string fileName = AdminAddDataFileName.Text;

        string cmd = "AddData" + MyVariables.DelimForTokens + fileName;
        doCommonPostback(cmd, sender);
    }

    protected void DoAdminAddPage(object sender, EventArgs e)
    {
        if (canSave() == false) return;

        string fileName = AdminAddPageFileName.Text;

        string cmd = "AddPage" + MyVariables.DelimForTokens + fileName;
        doCommonPostback(cmd, sender);
    }

    protected void DoRemoveCurrentPage(object sender)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        string cmd = "RemovePage" + MyVariables.DelimForTokens + currentPage.GetIndex().ToString();
        doCommonPostback(cmd, sender);
    }

    protected void ConvertAlertsToData(object sender, EventArgs e)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        string cmd = "ConvertAlertsToData";
        doCommonPostback(cmd, sender);
    }

    protected void HidePagesExceptCurrent(object sender, EventArgs e)
    {
        if (currentData == null) return;
        Data.Page currentPage = currentData.GetSelectedPage();
        if (currentPage == null) return;

        string cmd = "HidePagesExcept";
        doCommonPostback(cmd, sender);
    }

    protected void DoPopulateAdminSavePageExportedFileName(object sender, EventArgs e)
    {
        AdminSavePageExportedFileName.Text = ListofFilesInImportedDataDir.SelectedValue;
    }

    protected void DoPopulateAdminSaveProjectAs(object sender, EventArgs e)
    {
        AdminSaveAsProjectFileName.Text = AdminSaveAsProjectListBox.SelectedValue;
    }
    protected void DoPopulateAdminSaveProjectAsForNod(object sender, EventArgs e)
    {
        AdminSaveAsProjectFileNameForNod.Text = AdminSaveAsProjectListBoxForNod.SelectedValue;
    }


    protected void DoPopulateAdminAddDataFileName(object sender, EventArgs e)
    {
        AdminAddDataFileName.Text = AddDataFileNames.SelectedValue;
    }
    protected void DoPopulateAdminAddPageFileName(object sender, EventArgs e)
    {
        AdminAddPageFileName.Text = AdminAddPageFileNames.SelectedValue;
    }
    protected void MakeURL2_Click(object sender, EventArgs e)
    {
        closeAllDlgs();
    }

    private void doCalc(object sender, String request)
    {
        string serverCommand = "RepeatingCalculation" + MyVariables.DelimForTokens + request ;

        this.doCommonPostback(serverCommand, sender);
    }

    protected void JoinersAndLeavers_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        string arg = btn.CommandArgument;
        if (arg != "")
        {
            arg = arg.Replace(";ClosePanels", "" );

            string serverCommand = "SetMath" + MyVariables.DelimForTokens
                + SetMathPage1.SelectedValue.ToString() + MyVariables.DelimForTokens
                + SetMathPage2.SelectedValue.ToString() + MyVariables.DelimForTokens
                + arg;
            this.doCommonPostback(serverCommand, sender);
        }
    }

    protected void DoClearEventLog(object sender, EventArgs e)
    {
        EventLogZone.InnerHtml = "";
    }

    protected void DoCheckMoveRows(object sender, EventArgs e)
    {
        bool InFrontOfState = MoveRowsDestinationInstructions.SelectedValue.Equals("InFrontOf", StringComparison.CurrentCultureIgnoreCase);

        MoveRowsPosition.Enabled = MoveRowsPosition.Visible = InFrontOfState;
        RowIndexText.Visible = InFrontOfState;

        bool ActionState = MoveRowsAction.SelectedValue.Equals("Copy", StringComparison.CurrentCultureIgnoreCase);
        MoveRowsPagesText.Visible = ActionState;
        MoveRowsPages.Enabled = MoveRowsPages.Visible = ActionState;
    }
    protected void DoCheckMoveColumns(object sender, EventArgs e)
    {
        bool state = MoveColumnsDestinationInstructions.SelectedValue.Equals("InFrontOf", StringComparison.CurrentCultureIgnoreCase);

        MoveColumnsPosition.Enabled = MoveColumnsPosition.Visible = state;
        ColumnIndexText.Visible = state;

        bool ActionState = MoveColumnsAction.SelectedValue.Equals("Copy", StringComparison.CurrentCultureIgnoreCase);
        MoveColumnsPagesText.Visible = ActionState;
        MoveColumnsPages.Enabled = MoveColumnsPages.Visible = ActionState;
    }
    public void DoRunScriptFile(object sender, EventArgs e)
    {
        if (currentData == null)
            return;

        for (int i = 0, count = ScriptFiles.Items.Count; i < count; i++)
        {
            ListItem li = ScriptFiles.Items[i];
            if (li.Selected)
            {
                runScript(li.Value);
            }
        }
    }

}
